-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
  • 107,083
  • 22
  • 201
  • 376
JonSnow
  • 530
  • 10
  • 40

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,096
  • 23
  • 29
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
  • 8,226
  • 2
  • 18
  • 27
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,272
  • 5
  • 16
  • 27