React-Data-Table -Adding a Css Class to Row Dynamically

I am using an datatable of react-data-table-component, my table is generated from the API response data. I want to dynamically add a class to each of the rows generated based on the condition. How can I acheive this ?

I am using the above datatable.

let  columns= [
            {
                name: "ID",
                selector: "ID",
                sortable: true,
                cell: row => <div>{row.ID}</div>
            }];

<Datatable
columns={columns}
data={this.state.mydata} />

I want to add a custom CSS class to the entire row of this data table based on a condition.

2 Answers

I think you might be looking for the getTrProps callback in the table props:

getTrProps={ rowInfo => rowInfo.row.status ? 'green' : 'red' }

It's a callback to dynamically add classes or change style of a row element

Should work like this if I remember correctly:

getTrProps = (state, rowInfo, instance) => {
  if (rowInfo) {
    return {
      className: (rowInfo.row.status == 'D') ? "status-refused" : "", // no effect
      style: {
        background: rowInfo.row.age > 20 ? 'red' : 'green'
      }
    }
  }
  return {};
}

render() {

  <Datatable
  columns={columns}
  data={this.state.mydata} 
  getTrProps={this.getTrProps}
  />

}
7

example:

...
const conditionalRowStyles = [
  {
    when: row => row.calories < 300,
    style: {
      backgroundColor: 'green',
      color: 'white',
      '&:hover': {
        cursor: 'pointer',
      },
    },
  },
];
 
const MyTable = () => (
  <DataTable
    title="Desserts"
    columns={columns}
    data={data}
    conditionalRowStyles={conditionalRowStyles}
  />
);

more info check here :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest