Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

3 conditions – ternary conditional chains javascript react

So im just playing around with the rick and morty api and I’ve never done a ternary with 3 conditions. Mozilla docs says you can, but it’s not working for me. The code below shows the characters with the status alive in green and the rest are purple. I want alive to be green, dead to be red, unknown to be purple. Im using chakra ui if anyones curious. What am I doing wrong?

<Badge
  colorScheme={ c.status === "Alive" ? "green"
      : "unknown" ? "purple"
      : "red"
  }
>
  {c.status}
</Badge>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You have your symbols mixed up. Grouping with parentheses, your code is equivalent to

c.status === "Alive" ? "green"
      : ("unknown" ? "purple" : "red")

You need instead

c.status === 'Alive'
  ? 'green'
  : c.status === 'unknown' ? 'purple' : 'red'

Or you could use a lookup table instead – it’d be more readable.

const colorsByStatus = {
  Alive: 'green',
  unknown: 'purple',
  dead: 'red'
};

// ...

colorSceme={colorsByStatus[c.status]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading