Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Styling a text in react based on multiple conditions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{rows.map(row => (
                <TableRow key={row.id}>
                  <TableCell style={{ color: row.status === 'COMPLETED' ? 'green':''}} classes={{ root: classes.tableCell }} align="center">{row.status}</TableCell>
                  
                </TableRow>
              ))}

As you can see, its not that easy to do with ternary. Is there any other way to achieve this?

>Solution :

You can use a switch case to have multiple conditioning like below

function cellColor(status) {
  switch(status) {
    case 'COMPLETED': 
      return 'green';
    case 'BEGINNING': 
      return 'blue'
    case 'MIDDLE': 
      return 'red'
    case 'END': 
      return 'purple'
    case 'CONCLUSION': 
      return 'grey'    
    default: 
      return ''
  }
}


<TableCell style={{ color: cellColor(row.status)}} classes={{ root: classes.tableCell }} align="center">{row.status}</TableCell>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading