Formatting Material-UI table cells based on their content

I'm working on a Material UI table where I want to dynamically change the cell colors based on the values they display. The cells are populated with JSON data using mapping. For instance, if a cell contains the value 1, I'd like it to be displayed in yellow.


const data = [
  {
    Name: 'A Person',
    Attendance: [
      {
        date: '2019/12/01',
        attendance: 1
      },
      {
        date: '2019/12/02',
        attendance: 1
      },
      {
        date: '2019/12/03',
        attendance: 0
      }
    ]
  }
];

return (
  <Fragment>
    {data.map(person => (
      <Table>
        <thead>
          <tr>
            <th>Name</th>
            {person.Attendance.map(personAttendance => (
              <th>{personAttendance.date}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{person.Name}</td>
            {person.Attendance.map(personAttendance => (
              <td>{personAttendance.attendance}</td>
            ))}
          </tr>
        </tbody>
      </Table>
    ))}
  </Fragment>
);
}

export default Test;

This is what my table currently looks like. I attempted to use conditional rendering to change the background color of the cells:


if(value === 1) {
  return(
    <TableCell style={{ background: "yellow" }}>{value}</TableCell>
  )
} else {
  return(
    <TableCell style={{ background: "red" }}>{value}</TableCell>
  )
}

However, this approach didn't work as expected and everything ended up being displayed in red. Any suggestions on how to fix this issue would be greatly appreciated. Thank you!

Answer №1

Revise the tbody section in test.js as follows:

<tbody>
   <tr>
      <td>{person.Name}</td>
      {person.Attendence.map(personAttendendance => {
          if(personAttendendance.attendence === 1){
             return <td style={{background: "red" }}>{personAttendendance.attendence}</td>;
          } else {
             return <td style={{background: "blue" }}>{personAttendendance.attendence}</td>;
          }                  
      })}
   </tr>
</tbody>

Alternatively, you can use this version:

<tbody>
   <tr>
      <td>{person.Name}</td>
      {person.Attendence.map(personAttendendance => {
          return <td style={{background: personAttendendance.attendence === 1 ? "red" : "blue"}}>{personAttendendance.attendence}</td>;                
      })}
   </tr>
</tbody>

Choose the one that fits your needs better.

You can access the forked version here. (using the second example)

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

Having trouble getting the TailwindCSS container query to work with dynamically added elements

Trying to change Tailwind CSS queries into container queries where the className string is modified and placed back. The problem is that it's not being set to the component. Other styles work fine, just the container queries aren't working as exp ...

Should I only store one piece of state data in the state if multiple pieces always change together, and keep the rest in class variables instead?

Struggling to grasp what exactly needs to be maintained in state for plain React. Imagine having a main component <App> (holding all the state) and several other nested display components (only displaying passed props without any state). It appears ...

Traverse an array to generate a horizontal chart

My goal is to dynamically create a horizontal table by mapping through an array, similar to the design shown in this image. https://i.sstatic.net/YfElb.png This is how I am currently mapping through the array: const glanceGames = this.state.gameData.map ...

Whenever I adjust the zoom on my HTML page, it either scrolls upwards or downwards

Is there a way to prevent the page from scrolling when using zoom-in or zoom-out? I attempted using overflow: hidden in the body, but it did not work. <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

Why does the image resize with the window, yet a black bar appears on certain sizes?

Recently, I encountered a coding challenge where I needed to resize an image based on the window size of the web browser it's being viewed in: <p> <a href="www.link.com"> <img src="/images/image.png" style="max-height: 235px; ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

How can I access the dynamic page path in Next.js?

I'm currently working on implementing dynamic paths in my Next.js application. As part of a CMS system I'm developing, all pages are powered by Next.js. Within my React admin app, users have the ability to create and customize multiple pages. ...

How can a child component's height be dynamically adjusted according to its parent's size?

Here is a link to the codesandbox I created: https://codesandbox.io/s/jolly-agnesi-j5bzr?file=/src/App.js Below is a screenshot of the project: https://i.sstatic.net/GdYVZ.png The red background content is dynamically generated, causing the height of th ...

The revalidateTag and revalidatePath features in Next.js are currently not functioning as expected

I attempted to utilize the revalidateTag and revalidatePath functions with Next.js version 14.2.3. The objective was: there is a server action to fetch a list of items. also, there is a server action to add an item. upon successful addition of an item, I ...

Having trouble with Webpack not recognizing my HTML navigation links

I am setting up a new component in my webpack and encountered the following error message: ERROR in ./src/components/MainNav.js Module build failed: SyntaxError: Unterminated JSX contents (121:12) ReactDOM.render( > <MainNav/>, ...

Showing no background color until the user lifts their finger

I am currently in the process of developing a website. The navigation on the website starts off as transparent (background: transparent) when opened, but as soon as you start scrolling, it should transition to a colorful state with shades like grey, midnig ...

Grid items in Material UI are not positioned next to each other

I am encountering an issue with the Grid component in material-ui. The grid items are currently stacking below each other instead of beside each other, and I'm unsure of what is causing this behavior. My intention is for the grid items to stack on top ...

It appears that Nginx is having trouble locating the index.html file

After purchasing a VPS on Hostinger, I am facing an issue with deploying my app. The NodeJS server is up and running smoothly at bushnaq.group:8000. However, when I try to access my domain at bushnaq.group, it displays a 404 not found error. It seems like ...

Design a custom scrolling navigation bar for enhanced user experience

Struggling with web design as I develop a site in ASP.NET. I have a database full of courses, each with numerous modules. The challenge is creating a navigation bar that dynamically adjusts to accommodate the varying number of modules per course without o ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

Is it possible to incorporate another hue into Material UI's color palette?

I have a unique styleguide that I want to incorporate into Material UI. The Button's color prop currently has these options available: | 'default' | 'inherit' | 'primary' | 'secondary' However, I am in need of ...

Tips for making text flow around an image

How can I achieve a design where the text wraps around an image positioned in the bottom right corner? [Image Removed by Owner] Your guidance on implementing this effect is greatly appreciated. Thank you. ...

Adjust the scroll bar to move in the reverse direction

I'm trying to modify the behavior of an overlay div that moves when scrolling. Currently, it works as expected, but I want the scroll bar to move in the opposite direction. For example, when I scroll the content to the right, I want the scroll bar to ...

Error: The integer provided in the Stripe payment form is invalid in the

I'm encountering an error that I can't seem to figure out. I believe I'm following the documentation correctly, but Stripe is not able to recognize the value. Have I overlooked something important here? https://stripe.com/docs/api/payment_i ...

How can I effectively design a vertical table with a split background for optimal visual appeal?

Is there a way to creatively present this data with a split background using html and css? https://i.sstatic.net/qsCOM.png ...