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

Add different class depending on state

I have a div that needs some kind of background-color. The color depends on the value in the div which can be either negative, zero, or positive.

For example:

<div className={`colors ${value > 0 ? "green" : ""}`}>{value}</div>

With SCSS:

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

.colors {
    padding: 10px;

    &.green {
        background-color: green;
    }
 }

Would make the background-color green if the value is above 0. But how can I transform this so that if the value is zero then a neutral class with background-color grey is added, and a red class with background-color red if negative.

>Solution :

You’re very close there with the ternary; you can easily solve this by implementing nested ternary statements inside your template. Let’s say you have three CSS classes: green for positive, red for negative, and neutral for 0.

We can create a nested ternary to match all operations, something like this:

value > 0
  ? "green" // positive, make it green
  : value < 0
    ? "red" // negative, it's red
    : "neutral" // it's neither positive nor negative; it's 0; make it neutral

In your JSX that’d look something like:

<div className={`colors {
  value > 0
  ? "green"
  : value < 0
    ? "red"
    : "neutral"
}`>{value}</div>
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