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!