javascriptreactjsreact-tablereact-table-v6

color cell based on the result of another column in react-table-6


Current I am displaying the table as such where the cell in the Protected column is highlighted green if True and red if False:

Name |     Source     | Protected
________________________________
Ryan      Computer       False
Briana Phone, Computer   True
Shawn      Phone         True
Serge      Phone         False

My corresponding code looks like this:

const columns = [
      {
        Header: "Name",
        accessor: "Name",
        style: {
          textAlign: "center",
        },
      },
      {
        Header: "Source",
        accessor: "Source",
        style: {
          textAlign: "center",
        },
      },
      {
        Header: "Protected",
        id: "Protected",
        accessor: (d) => d.protected.toString(),
        getProps: (state, rowInfo) => {
          if (rowInfo && rowInfo.row) {
            return {
              style: {
                textAlign: "center",
                background: rowInfo.row.protected === "false" ? "red" : "green",
              },
            };
          } else {
            return {};
          }
        },
      },
    ];

Is it possible to drop the Protected column and highlight the Source column with red or green based on if the corresponding Protected attribute is true or false? i.e.

Name |     Source (highlighted color)   
_____________________________________
Ryan       Computer  (red)     
Briana     Phone, Computer (green)  
Shawn      Phone (green)      
Serge      Phone (red)       

My data looks like this:

[
  {
    "Name": "Ryan",
    "Protected": false,
    "Source": ["Computer"],
  },
  {
    "Name": "Briana",
    "Protected": true,
    "Source": ["Phone, Computer"],
  },
  {
    "Name": "Shawn",
    "Protected": true,
    "Source": ["Phone"],
  },
  {
    "Name": "Serge",
    "Protected": false,
    "Source": ["Phone"],
  }
]

Solution

  • Yes, it's possible.

    To do so, when creating your columns, you can affect the style of it with the Cell props, and adding a <div /> around your data's content.

    Like this:

    columns = [
      {
        Header: "Source",
        accessor: "Source",
        style: {
          textAlign: "center",
        },
        Cell: (row) => {
          return (
            <div style={{ background: row.original.Protected === 'true' ? 'green' : 'red' }}>
              {row.original.Source}
            </div>
          );
        },
      });
    ];