Clue Mediator

Conditionally change the row style in React DataTable

๐Ÿ“…July 25, 2021
๐Ÿ—ReactJS

In this article, we will show you how to conditionally change the row style in React DataTable.

Checkout more articles on DataTable

Demo Application

Output - Conditionally change the row style in React DataTable - Clue Mediator

Output - Conditionally change the row style in React DataTable - Clue Mediator

You may also like the following articles on ReactJS

Steps to change the row style in React DataTable

  1. Implement datatable in the react application
  2. Apply the conditional style using conditionalRowStyles
  3. 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..!! ๐Ÿ™‚

Demo & Source Code

GitHub Repository StackBlitz Project