-1

How do I handle the following:

const SpeedTest = ({ speed }) => (
  <div {speed > 80 ? {{style=color:red}} : {{style=color:green}} }>
    {speed > 80 ? "Too fast!" : "All fine"}
  </div>
);

Conditional text change works fine, but I am not able to get the color change done.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
JonSnow
  • 573
  • 14
  • 48

4 Answers4

1

This is what you are looking for

const SpeedTest = ({ speed }) => (
  <div style={{ color: speed > 80 ? "red" : "green" }}>
    {speed > 80 ? "Too fast!" : "All fine"}
  </div>
);
Moinul Hossain
  • 2,176
  • 1
  • 24
  • 30
1

You can do like this (remember to use quotes around inline styling values):

const SpeedTest = ({ speed }) => (
  <div style={{ color: speed > 80 ? 'red' : 'green' }}>
    {speed > 80 ? "Too fast!" : "All fine"}
  </div>
);
  • ah, I need to set the condition inside of the style declaration - that does the trick. thank you! – JonSnow Dec 30 '19 at 09:10
1

Corrected

const SpeedTest = ({ speed }) => (
  <div style={{color: speed>80 ?'red':'green'}}>
    {speed > 80 ? "Too fast!" : "All fine"}
  </div>
);
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
1

you can hold style in the variable and then change its value based on condition

  const SpeedTest = ({ speed }) => {
   let style={}
     if(speed>80){
        style={color:'red'}
     }else{
        style={color:'green'}
     }
    return (
      <div style={style}>
         {speed > 80 ? "Too fast!" : "All fine"}
     </div>
    )
   };
Jatin Parmar
  • 2,759
  • 5
  • 20
  • 31