n_d22
n_d22

Reputation: 513

Nested Conditional Styling with CSS/JavaScript

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.

Upvotes: 0

Views: 101

Answers (2)

F&#233;lix Paradis
F&#233;lix Paradis

Reputation: 6031

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)} }
>

Upvotes: 1

Matt B.
Matt B.

Reputation: 59

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'

Upvotes: 1

Related Questions