Home > Net >  Add different class depending on state
Add different class depending on state

Time:05-28

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:

.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.

CodePudding user response:

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>

CodePudding user response:

Also, you can try this:

const bgColor = new Map([
  [false, "negative"],
  [true, "positive"],
  [0, "neutral"],
]);

<div className={`colors ${bgColor.get(value)}`}>{value}</>
  • Related