user11951305
user11951305

Reputation: 41

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 ?

https://www.npmjs.com/package/react-data-table-component

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.

Upvotes: 4

Views: 13006

Answers (2)

Yixuan HUANG
Yixuan HUANG

Reputation: 31

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 :) https://www.npmjs.com/package/react-data-table-component#conditional-row-styling

Upvotes: 3

Anton Bks
Anton Bks

Reputation: 492

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}
  />

}

Upvotes: 3

Related Questions