Modifying Table Cell Background Color in ReactJS: A Guide to Conditionally Updating Cell Color Without Affecting the Entire Row

I am working on changing the background color of a cell based on its value.
Currently, I am utilizing the following library: react-data-table-component

Procedure:

  • If the value is above 0, then the cell's background color will be red.
  • Otherwise, there will be no background color.

Here is my code snippet 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,
                },
            ]
        }
    />  
);
}

Below is an image showing the expected result:

https://i.stack.imgur.com/z2t2E.jpg

Answer №1

By referring to the documentation, you can implement conditional styles in this manner: 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',
      },
    },
  },
  // Additional customization using a callback for styling
  {
    when: row => row.calories < 300,
    style: row => ({
      backgroundColor: row.isSpecial ? 'pink' : 'inherit',
    }),
  },
];

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

An example incorporating cell and styled components is available here:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for maintaining the webcam video in the center of the screen even when the height is set to 100% and the window is being resized

When using React, I encountered an issue with centering a webcam video while maintaining its height at 100% of the screen. Although the video fills the screen vertically correctly, adjusting the width of the window causes the video to lose its centered pos ...

Nextjs faces extended delays during user verification with Firebase Authentication

I am running a react application that utilizes firebase authentication. Within my global context, I have implemented a useEffect function to handle the actions related to the currently logged-in user: useEffect(() => { const unsubscribeAuth = fireb ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

AngularJs - Show the response only upon verifying the correct answer

Let me provide an overview of what has been implemented so far: When a user selects an answer in radio buttons and clicks on "Check Answer", the system displays either "Correct" (in green) or "Incorrect" (in red) in the first answer field. Additionally, th ...

Ways to ensure that the dropdown content remains visible even after the mouse has exited the trigger element

There are three buttons arranged in a row, and when one is hovered over, dropdown content appears underneath all three buttons. However, the content disappears when the mouse moves down to it. Unfortunately, images cannot be posted inside yet** https://i.s ...

Why do I continue to encounter the error message saying 'jQuery is not defined'?

As a newcomer to the world of jQuery and Visual Studio Environment, I embarked on the journey of creating a circular navigation menu bar following the instructions provided in this link. Despite my efforts, I encountered a hurdle in the head section where ...

Why isn't my NextJs function displaying on another NextJs page?

I recently encountered an issue while developing my NextJs app. I have a function in the 'Feed.tsx' page that is not rendering properly inside the 'Index.tsx'. Strangely, when I navigate to '/feed', the function works perfectl ...

Tips for incorporating an image into the background of a mobile device

My attempt to set an image as a background was successful on desktop, but unfortunately, it doesn't work on my phone. I have specified 'cover' as the background-size, expecting it to cover all the space on mobile as well. Here is the code s ...

Breaking apart field values in React Final Form

In my react and redux application, I am using react final form with a 'cars' field that is a select. When the submit event is triggered, it should only return specific types like coupe: ['BMW'] instead of just the field name with values ...

How can I modify the preset website design in React.js (vite)?

Whenever I start a new react js project, I am always met with the default template that includes unnecessary code. I find myself spending time navigating through different files to clean it up before I can start building. I've been searching for a bla ...

What is the best way to align icons in the center alongside text or paragraphs using react?

I'm struggling with centering my icons like <GrTools size="30px"/> next to my text. It's causing some alignment issues with my styled components. Here is my JavaScript: <div id='paragraph' className="container"> ...

Is there a way to eliminate the underline in TextField components in Material-UI?

Is there a way to remove the underline from a material-ui TextField without using InputBase? I would prefer to stick with the TextField API, but have not been able to find a solution in the documentation. ...

Display a Bootstrap table that includes a visible vertical scrollbar

Creating a basic HTML page using Bootstrap library can be tricky when trying to incorporate a fixed header and a scrolling table. When simply adding a navbar and a table, the table ends up being positioned beneath the navbar, making it impossible to scroll ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

What steps should I take to implement Role-Based Access Control in my Spring/React application?

I am currently working on integrating an Admin Dashboard React Bootstrap Template with a separate REST API built using Spring to query a Postgres DB. The frontend fetches data from this API. My main challenge is implementing different user roles that wi ...

Transform colored svg:image elements into grayscale when clicked upon by utilizing d3

Visit this site I'm attempting to change all SVG images created using d3.select to grayscale by using the following function: JavaScript: <script> function convert() { d3.selectAll("image") .style('filter', 'graysc ...

Tips for triggering a click event automatically after a 2-minute delay in ReactJS using TypeScript

I need assistance automating a button's onClick function to execute after a 2-minute delay. The current button invokes the handleEventVideos() function. What is the best way to automatically trigger the button click after 2 minutes? I had tried creat ...

How to Place a Button Halfway Out of an Angular 5 Material Dialog

Is there a way to place a close button on the top right corner of a dialog box, partially inside and outside the dialog like shown in this image: I attempted using absolute positioning to achieve this, but that solution is not ideal. I want to position t ...

Is it possible to adjust the default zoom level of my website by utilizing HTML or CSS?

After creating my website with a 50% zoom setting, I've encountered an issue where it appears too zoomed in for users whose browser default is set at 100%. How can I fix this problem? I attempted to use *{zoom:50%} in CSS to set the default zoom leve ...

How come I am unable to vertically align my elements with bootstrap?

Currently, I am in the process of developing a windsurfing website. Despite utilizing classes such as justify-content-center, align-items-center, and text-center, I am facing an issue where the h1 and h2 elements remain positioned at the top and are not ve ...