admin管理员组

文章数量:1302277

I am using an datatable of react-data-table-ponent, 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.

I am using an datatable of react-data-table-ponent, 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./package/react-data-table-ponent

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.

Share edited Aug 20, 2019 at 11:45 Vinay Hegde 1,4601 gold badge13 silver badges24 bronze badges asked Aug 20, 2019 at 11:40 user11951305user11951305 411 gold badge1 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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}
  />

}

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./package/react-data-table-ponent#conditional-row-styling

本文标签: javascriptReactdatatable Adding a CSS class to row dynamicallyStack Overflow