Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-table Individual Cell Style

I am using react-table and want to change the background color of specific cells based on their number inside. Ex. Cell > 1 = green, Cell < 1 = Red, and different shades in-between. I have seen a ton of stuff about coloring rows and columns, but am struggling on how to color specific cells based on the data that is loaded.

I know this code doesn't work, but hopefully it will show kind of what I am looking for:

<ReactTable
  data={data}
  columns={columns}
  getTdProps={(cellInfo) => {
      return {
        if (cellInfo.value > 1) {
            cellInfo.className = "green-cell";
        }
        if (cellInfo.value < 1) {
            cellInfo.className = "red-cell";
        }
      };
    }}
/>

Hopefully that makes sense. Thanks for the help.

like image 837
David Avatar asked Dec 21 '18 17:12

David


1 Answers

If you're using v7 react-table, use getCellProps

  <Table
    columns={[
      {
        Header: "Age",
        accessor: "age"
      }
    ]}
    data={[{ age: 8 }, { age: 11 }, { age: 9 }, { age: 6 }, { age: 12 }]}
    getCellProps={(cellInfo) => ({
      style: {
        backgroundColor: cellInfo.value > 10 ? "red" : null
      }
    })}
  />

https://codesandbox.io/s/magical-yalow-g22yz?file=/src/App.js:2447-2459

like image 173
sanme98 Avatar answered Oct 11 '22 00:10

sanme98