4

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.

2 Answers 2

3

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

}
Sign up to request clarification or add additional context in comments.

7 Comments

can you give an example ?
Im checking the docs now; the name of this props seems to have changed, give me a sec to update my answer
Also added the className property that allows you to conditionally assign a class
Sorry but this didnt work for me. Do you have any alternative for the same? I want to add a custom class to the row with the class name as rdt_TableRow of the row.
What is your condition for adding the class? Can you post the updated code with what you have tried from the above please?
|
3

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.