Conditionally change the row style in React DataTable
In this article, we will show you how to conditionally change the row style in React DataTable.
Checkout more articles on DataTable
- How to implement DataTable in React
- Datatable with pagination in React
- Server side pagination with React DataTable
Demo Application
Output - Conditionally change the row style in React DataTable - Clue Mediator
You may also like the following articles on ReactJS
- Get the country flag from the country code in React
- Barcode scanner in React
- Implement server side pagination in React AG Grid
- Test an input field using the React Testing Library
- Implement multi-languages in React
Steps to change the row style in React DataTable
- Implement datatable in the react application
- Apply the conditional style using conditionalRowStyles
- Output
1. Implement datatable in the react application
First, create a react application using the `create-react-app` npm package and add the datatable in the application.
Refer the following article, if you donโt know about the datatable implementation.
How to implement DataTable in React
2. Apply the conditional style using conditionalRowStyles
Here, we will change the background of the row based on the email address and phone number using the `conditionalRowStyles` property.
App.js
...
...
function App() {
const conditionalRowStyles = [
{
when: row => row.email.includes('.org'),
style: {
backgroundColor: 'green',
color: 'white',
'&:hover': {
cursor: 'pointer',
},
},
},
// You can also pass a callback to style for additional customization
{
when: row => row.email.includes('.com'),
style: row => ({
backgroundColor: row.phone.startsWith('9') || row.phone.startsWith('1') ? 'pink' : 'inerit',
}),
},
];
return (
<div class="App">
<h3>Conditionally change the row style in React DataTable - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h3>
<datatable title="Employees" columns={columns} data={data} pagination="" highlightonhover="" conditionalrowstyles={conditionalRowStyles}>
</datatable></div>
);
}
export default App;
Checkout more articles on The `conditionalRowStyles` contains two properties.
- when - `when` accepting a callback that gives you access to your row data. The `when` callback must return a boolean to determine if the style will be applied.
- style - Accepts a css-in-js style object. Alternatively, you can also specify a callback that has access to the row props.
3. Output
Run your react application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐