ReactJS 7 – How to conditionally change the background color of table cell only (not the row) based on its value?

Issue

I am trying to change the background color of the cell based on its value inside.
I am currently using this library: react-data-table-component

Logic:

  • If value is greater than 0, then the background color of the cell will be red.
  • Otherwise there won’t be a background color.

Here’s my current snippet code for the Data Table:

const CountryTable = ({items}) => {

return(
    <DataTable
        title="Covid-19 Stats"
        defaultSortAsc="false"
        responsive
        defaultSortField="cases"
        defaultSortAsc={false}
        striped
        highlightOnHover
        data={items}
        columns={
            [
                {
                    name: '#',
                    selector: (row, index) => index+1,
                    disableSortBy: true,
                },
                {
                    name: 'Country',
                    selector: 'country',
                    sortable: true,
                },
                {
                    name: 'Total Cases',
                    selector: 'cases',
                    sortable: true,
                },
                {
                    getProps: (state, rowInfo) => {
                        if (rowInfo && rowInfo.row) {
                        return {
                            style: {
                            background:
                                parseInt(rowInfo.row.todayCases) > 0 ? "red" : null
                            }
                        };
                        } else {
                        return {};
                        }
                    },
                    name: 'Additional New Cases',
                    selector: 'todayCases',
                    sortable: true,
                },
                {
                    name: 'Current Active Cases',
                    selector: 'active',
                    sortable: true,
                },
                {
                    name: 'Total Deaths',
                    selector: 'deaths',
                    sortable: true,
                },
                {
                    name: 'Additional New Deaths',
                    selector: 'todayDeaths',
                    sortable: true,
                },
                {
                    name: 'Total Recoveries',
                    selector: 'recovered',
                    sortable: true,
                },
                {
                    name: 'Additional New Recoveries',
                    selector: 'todayRecovered',
                    sortable: true,
                },
            ]
        }
    />  
);
}

And here’s the illustration of what it should be look like:

enter image description here

Solution

The docs say you can set conditional styles like this: https://www.npmjs.com/package/react-data-table-component#conditional-style-object

const conditionalRowStyles = [
  {
    when: row => row.calories < 300,
    style: {
      backgroundColor: 'green',
      color: 'white',
      '&:hover': {
        cursor: 'pointer',
      },
    },
  },
  // You can also pass a callback to style for additional customization
  {
    when: row => row.calories < 300,
    style: row => ({
      backgroundColor: row.isSpecia ? 'pink' : 'inerit',
    }),
  },
];

const MyTable = () => (
  <DataTable
    title="Desserts"
    columns={columns}
    data={data}
    conditionalRowStyles={conditionalRowStyles}
  />
);

I quickly put together an example usings cell and styled components:

https://codesandbox.io/s/upbeat-galileo-r7p34?file=/src/App.js

import "./styles.css";
import DataTable from "react-data-table-component";
import styled from "styled-components";

const StyledCell = styled.div`
  &.low {
    background: green !important;
  }
  &.medium {
    background: orange;
  }
  &.high {
    background: red !important;
  }
`;

export default function App() {
  let items = [
    {
      Country: "Canada",
      AdditionalNewCases: 500
    },
    {
      Country: "England",
      AdditionalNewCases: 5000
    },
    {
      Country: "USA",
      AdditionalNewCases: 500000
    }
  ];
  function getCssClass(value) {
    if (value > 5000) return "high";
    else if (value > 500) return "medium";
    return "low";
  }
  return (
    <DataTable
      title="Covid-19 Stats"
      defaultSortAsc="false"
      responsive
      defaultSortAsc={false}
      striped
      highlightOnHover
      data={items}
      columns={[
        {
          name: "number",
          selector: (row, index) => index + 1,
          disableSortBy: true
        },
        {
          name: "Country",
          selector: "Country",
          sortable: true
        },
        {
          name: "New Cases",
          selector: "AdditionalNewCases",
          sortable: true,
          cell: (row) => (
            <StyledCell className={getCssClass(row.AdditionalNewCases)}>
              {row.AdditionalNewCases}
            </StyledCell>
          )
        }
      ]}
    />
  );
}

Answered By – Sir Codes Alot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published