React-table Individual Cell Style
27,353
Solution 1
getTdProps
is for the entire row. Use getProps
in the column definition instead. For example:
<ReactTable
data={[
{ age: 8 },
{ age: 11 },
{ age: 9 },
{ age: 6 },
{ age: 12 },
]}
columns={[
{
Header: 'Age',
accessor: 'age',
getProps: (state, rowInfo, column) => {
return {
style: {
background: rowInfo && rowInfo.row.age > 10 ? 'red' : null,
},
};
},
}
]}
/>
Solution 2
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
Author by
David
Updated on July 31, 2022Comments
-
David almost 2 years
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.
-
Johhan Santana over 4 yearsis there a way to edit the
Header
style as well? or do we need to return JSX in theHeader
key? -
nebuler over 4 yearsThere is @JohhanSantana - add
headerStyle
property right under accessor. It works the same waystyle
works for react components. -
Hrithik Naha about 3 yearsThis doesnt work anymore for v7. Any solution for v7?
-
nathaneast over 2 yearsthank you! your question is working!