Search code examples
reactjsreact-table-v7

Is there a way to style individual cell using react-table based on the value?


I want to style individual cell in react-table but I am not able to do so.

const MOCK_DATA = [
  {
    amount: 1000,
    status: `SUCCESS`,
    updatedAt: 1629181927,
  },
  {
    amount: 2000,
    status: `FAILED`,
    updatedAt: 1629181927,
  },
];
export const COLUMNS = [
  {
    Header: 'Date',
    accessor: 'transactionDate',
  },
  {
    Header: 'Amount',
    accessor: 'amount',
  },
  {
    Header: 'Status',
    accessor: 'status',
  },
];

This is the jsx:

 <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          );
        })}
      </tbody>

Let suppose I want to change the color of the cell to green or red based on the status of the data how can I achieve that?

Note:


Solution

  • You can make use of the custom cell render option in react-table .

      {
            Header: "Status",
            accessor: "status",
            Cell: (props) => {
              return (
                <p style={{ color: props.value === "SUCCESS" ? "green" : "red" }}>
                  {props.value}
                </p>
              );
            }
          }
    

    Working Sandbox

    when there are multiple status and needs to show different color for each status we can maintain a map .

    const statusColorMap =  {
      SUCCESS: 'green',
      FAILED: 'red',
      PENDING: 'yellow'
      // etc 
    }
    

    Now we can do this

    <p style={{ color: statusColorMap[props.value] }}>{props.value}</p>;