How to dynamically change Material UI Table cell backgrounds with Javascript based on cell values?

This question is quite basic, but I'm struggling to understand it. I am working with React and JS and want to change the background of the "Charge Left" cell based on its value. For example, if the charge is less than 30, the background should be red; if the charge is between 31 and 59, it should be orange; and if the charge is greater than 59, it should be green.

I've tried various solutions in JS, but I can't seem to get any of them to work.

<StyledTableCell align="center">{user.chargeLeft}</StyledTableCell>

import React, { useEffect, useState } from "react";
import "./App.css";
import "./colorChange.jsx";
import Amplify, { API, graphqlOperation } from "aws-amplify";
import awsconfig from "./aws-exports";
import { AmplifySignOut, withAuthenticator } from "@aws-amplify/ui-react";
import { listChargeProfiles } from "./graphql/queries";

import logo from "./evslogo.png";

import { Paper } from "@material-ui/core";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";

Amplify.configure(awsconfig);

function App() {
  const StyledTableCell = withStyles(theme => ({
    head: {
      backgroundColor: theme.palette.common.black,
      color: theme.palette.common.white,
      fontSize: 18,
      fontWeight: "bold"
    },
    body: {
      fontSize: 16
    }
  }))(TableCell);

  const StyledTableRow = withStyles(theme => ({
    root: {
      "&:nth-of-type(odd)": {
        backgroundColor: theme.palette.action.hover
      }
    }
  }))(TableRow);

  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchUserData();
  }, []);

  const fetchUserData = async () => {
    try {
      const userData = await API.graphql(graphqlOperation(listChargeProfiles));
      const userList = userData.data.listChargeProfiles.items;
      setUsers(userList);
    } catch (error) {
      console.log("Failed to Return Users.", error);
    }
  };

  const useStyles = makeStyles({
    table: {
      minWidth: 700
    }
  });

  const classes = useStyles();

  return (
    <div className="App">
      <header className="evs-header">
        <div className="container">
          {/* EVS Logo */}
          <img src={logo} alt="Evs Energy Logo" className="logoEvs" />
          <div className="vertical-divider"></div>
          <p className="charge-text">
            Charging <br />
            Profile
          </p>
        </div>
        <AmplifySignOut />
      </header>
      {/* Page Divider */}
      <div className="evs-header-bar"></div>
      <TableContainer component={Paper}>
        <Table className={classes.table} aria-label="customized table">
          <TableHead>
            <TableRow>
              <StyledTableCell align="center">First Name</StyledTableCell>
              <StyledTableCell align="center">Last Name</StyledTableCell>
              <StyledTableCell align="center">Email</StyledTableCell>
              <StyledTableCell align="center">Car Model</StyledTableCell>
              <StyledTableCell align="center">Charge Level</StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {users.map(user => (
              <StyledTableRow>
                <StyledTableCell align="center">
                  {user.firstName}
                </StyledTableCell>
                <StyledTableCell align="center">
                  {user.lastName}
                </StyledTableCell>
                <StyledTableCell align="center">{user.email}</StyledTableCell>
                <StyledTableCell align="center">
                  {user.carModel}
                </StyledTableCell>
                <StyledTableCell align="center">
                  {user.chargeLeft}
                </StyledTableCell>
              </StyledTableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Footer Section */}
      <footer className="evs-footer">
        <div className="container">
          <p className="footer-text">About</p>
          <p className="footer-text">Help Centre</p>
        </div>
      </footer>
    </div>
    // </div>
  );
}

Answer №1

I have developed a fresh file for the StyledTableCell and set up the styles within it. It's worth mentioning that you can utilize props inside makeStyles to adjust styles based on props. For more information, click here.

Additionally, you have the option to pass your root class to the TableCell through the classes prop.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TableCell from "@material-ui/core/TableCell";

const useStyles = makeStyles((theme) => ({
  root: {
    background: (props) => {
      if (props.charge <= 30) {
        return "blue";
      } else if (props.charge >= 31 && props.charge <= 59) {
        return "orange";
      }
      else {
        //props.charge > 5
        return "green";
      }
    },
  },
}));
const StyledTableCell = (props) => {
  const classes = useStyles2(props);
  return (
    <TableCell
      classes={{
        root: classes.root,
      }}
    >
      {props.children}
    </TableCell>
  );
};

export default StyledTableCell;

In your main file, you would then assign your charge prop to the new component:

...
import StyledTableCell from "./StyledTableCell";

...
<StyledTableCell align="center" charge={user.chargeLeft}>
    {user.chargeLeft}
</StyledTableCell>

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

How can I automatically add and remove the active class to the navigation on a single page layout?

Is there a way to automatically add an active class to the navbar links when a specific navigation section appears as you scroll down a one-page layout? Similarly, can the active class continue to move to the corresponding section in the nav links as you s ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...

Real-time chart updates in ReactJS with automatic input change detection

Trying to automatically update a chart when input changes has been my challenge. With an input field (k), an array containing two columns (x and sin(kx)), and a chart displaying sin(kx), I am hoping for the array and chart to update seamlessly as k changes ...

When the page is refreshed, reorienting axes in three.js encounters difficulties

I am currently working on a project that involves using the three.js editor source code available for download on the three.js website. As part of this project, I am required to adjust the orientation of the axes to align with standard airplane coordinate ...

How to centrally position an image within a div using Bootstrap

I am a fan of using bootstrap and I recently encountered an issue with applying max-width to an image. It seems that when I do this, the image does not center properly despite using text-center. The solution I found was simply removing the max-width to ...

Is it possible for promises and $(data).each in jQuery not to work together?

My AJAX handler contains an each() loop to push data into my temp array. However, I am encountering an issue where the array remains empty after the loop. This is puzzling, as I have used promises with each() before without any problems. var temp = []; $. ...

Struggling with incorporating GlobalStyles in the app.tsx file

I have been working with next13 and styled-components. Initially, everything seemed fine in my file globalStyles.ts, and all was functioning perfectly. However, I started encountering errors related to the import of <GlobalStyles/>. Specifically, th ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...

What is the method for deactivating body parser json and urlencoded specifically on certain website links?

let shouldParseRequest = function (req) { let url = req.originalUrl; return (url.startsWith('/api/payments/stripe-webhook') || url.startsWith('/uploadimg')); } let parseJSON = bodyParser.json({ limit: '900kb' }); let u ...

Switch out the keyup event action for a click event action

http://jsfiddle.net/2q8Gn/23/ I am looking to modify the provided fiddle so that instead of having computedPageLinks update with each key press in the search input, it updates only when a button is clicked and does not change when the search input loses f ...

Linking several asynchronous functions together in JavaScript

class Calculation { constructor(num) { this.num = num; } performAddition() { // code } performSubtraction() { // code } performMultiplication() { // code } performDivision() { // code } } const getResult = async ...

Code for a regular expression that permits either letters or numbers with symbols

Here is the code snippet I am using for data validation in jQuery: return /^(?=.*[A-Za-z0-9/\$#.-_])[A-Za-z0-9/\$#.-_]$/i.test(value) The requirement is that the value should begin with letters or numbers, or a combination of both. Afterwards, ...

How can I customize the clock's background color in material-ui pickers?

Currently, the material-ui/pickers^3.2.6 has a theme with primary color gray and Clock background color also set to gray, causing the selected time circle and line to disappear. The issue is clearly visible in this image. I am looking for a solution to ove ...

Switch out 2 Bootstrap columns for 2 concealed columns with just a click. Utilizing Rails 4 and Bootstrap

Using Twitter Bootstrap 3 for a column system showcasing four similar advertisements at the bottom of the page. Code Snippet: <div class="row similar"> <% @recomended_ads.each do |advertisement| %> <div class="col- ...

Using computed properties with v-for - a comprehensive guide

In a current project, I have a component in which I am using v-for to iterate over a draggable JS component. <div v-for="(val, index) in rows" :key="index"><draggable></draggable/></div> The property rows in my ...

Ways to compel divs underneath aligned divs

There are six divs numbered 1 to 6. I want divs 2, 4, and 6 to be positioned below divs 1, 3, and 5 respectively. Is it possible to achieve this layout? Sorry if my explanation is not very clear. Thank you. http://jsfiddle.net/LkGV8/ <body> <d ...

Clearing form data after submitting in Laravel using axiosIn Laravel, utilizing

When working on my Laravel app, I encountered an issue while submitting a form using Vue and Axios. Despite my attempts to clear the input field after submission, it doesn't seem to work. HTML: <form method="post" enctype="multipart/form-data" v- ...

Notifying Incorrect Reading on Slider Display

My slider is supposed to alert the output on a button click based on its value, but it always alerts 2 instead of the expected values of 1, 2, 3, or 4. Here is the code I am using: var chanceoflive3; var inputElement = document.querySelector('.rang ...

Utilize jQuery to eliminate a parameter name and its corresponding value from a URL

Original Web Address http://example.com/home.php?id=1&branch_id=4&course_id=5 Updated Website URL http://example.com/home.php?id=1&branch_id=4 Deleting course_id from the existing website link Is there a way to eliminate a parameter value ...

Implementing batch processing and scheduling API requests in node.js using async functions

I am currently working on analyzing a social network graph, specifically focusing on creating a "six degrees of separation" tree based on adjacency lists obtained from an API. The challenge lies in the fact that there is a large number of individuals in t ...