Home > Software design >  Nested Conditional Styling with CSS/JavaScript
Nested Conditional Styling with CSS/JavaScript

Time:08-17

In my React app I have a box which is styled. The component holds state. I would like to change the colour of the box dependant on the colour.

For example, if selectedID = 1, pink, if selectedID = 2, green etc and so on.

I've tried something like this with no success:

<InformationContainer
// style={ {backgroundColor: selectedID < 2  || selectedID > 2 ? '#ebedfb':'#ffe5e5'}}
style={ {backgroundColor: 
selectedID < 4 ? '#ffe5e5':
selectedID < 3  || selectedID > 2 ? '#414c97':
selectedID < 3  || selectedID > 3 ? '#65bb2c':
selectedID < 3  || selectedID > 3 ? 'yellow':
'white'
}}
>

I would like o have this for all 4 boxes and pieces of state.

CodePudding user response:

To me it seems like the selectedID will always be less than four so it never makes it past the first check. As well some of your checks don't make sense. Something like this would work better.

style={ {backgroundColor: 
    selectedID == 4 ? '#ffe5e5':
    selectedID == 3 ? '#414c97':
    selectedID == 2 ? '#65bb2c':
    selectedID == 1 ? 'yellow':
    'white'

CodePudding user response:

If you're not a big fan nested ternaries (I'm not), you could extract that logic in a small function.

getBgColor(selectedID) {
  if(selectedID === 4) return '#ffe5e5';
  if(selectedID === 3) return '#414c97';
  if(selectedID === 2) return '#65bb2c';
  if(selectedID === 1) return '#yellow';
  return 'white';
}
// ***
<InformationContainer
  style={ {backgroundColor: getBgColor(selectedID)} }
>
  • Related