I am using react and trying to see how to style some text based on multiple condtions. The conditions are based on status. So I have a map function that is iterating over an array of rows and they all have a status field. The five status’ are:
‘INTRO’ ‘BEGINNING’ ‘MIDDLE’ ‘END’ ‘CONCLUSION’
So i want intro status to be green, beginning status to be blue, middle status to be red, end status to be purple, and conclusion status to be grey. I tried to do this with ternary operators but it seems it can only be achieved with two colors. For example:
JavaScript
x
6
1
{rows.map(row => (
2
<TableRow key={row.id}>
3
<TableCell style={{ color: row.status === 'COMPLETED' ? 'green':''}} classes={{ root: classes.tableCell }} align="center">{row.status}</TableCell>
4
</TableRow>
5
))}
6
As you can see, its not that easy to do with ternary. Is there any other way to achieve this?
Advertisement
Answer
You can use a switch case to have multiple conditioning like below
JavaScript
1
20
20
1
function cellColor(status) {
2
switch(status) {
3
case 'COMPLETED':
4
return 'green';
5
case 'BEGINNING':
6
return 'blue'
7
case 'MIDDLE':
8
return 'red'
9
case 'END':
10
return 'purple'
11
case 'CONCLUSION':
12
return 'grey'
13
default:
14
return ''
15
}
16
}
17
18
19
<TableCell style={{ color: cellColor(row.status)}} classes={{ root: classes.tableCell }} align="center">{row.status}</TableCell>
20