0

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.

3
  • What is the issue you are having, no background color at all or just sticks with some value and doesn't change? Can you also show how you set selectedID? Commented Aug 16, 2022 at 15:07
  • All that logic should be extracted to a function (or just a data object) on the parent component. Markup should be kept clean. Commented Aug 16, 2022 at 15:31
  • An ID is a string. How are you comparing to integers? Commented Aug 16, 2022 at 15:33

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.