Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Styled Components conditional ternary operator

I'm trying to conditionally style a box with three different colors depending on the value of my test.

if test = A or B, it needs to be yellow
if test = C, it needs to be green,
if test = anything else, it needs to be blue.

I would rather write a switch or if/else, but I don't know if its possible to not use a ternary operator with Styled Components.

like image 907
xyzcode Avatar asked Dec 13 '22 15:12

xyzcode


1 Answers

props => ... is just an arrow function with implicit return, so you could give the arrow function a body and accomplish what you want with if/else statements.

You could use props.data && props.data.test to make sure that props.data is set before you try to access test.

color: ${props => {
  const test = props.data && props.data.test;

  if (test === 'A' || test === 'B') {
    return 'yellow';
  } else if (test === 'C') {
    return 'green';
  } else {
    return 'blue';
  }
}};
like image 111
Tholle Avatar answered Dec 18 '22 00:12

Tholle