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
Demo Application
You may also like the following articles on ReactJS
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | ... ... 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 className="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} /> </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. Thewhen
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..!! 🙂