React-table Individual Cell Style

David picture David · Dec 21, 2018 · Viewed 18.4k times · Source

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:

Hopefully that makes sense. Thanks for the help.

Answer

nebuler picture nebuler · Dec 21, 2018

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,
                    },
                };
            },
        }
    ]}
/>