bryan
bryan

Reputation: 9369

Reactjs multiple if className's

I have the following element:

<div className="safety-bar"></div>

I also have 2 classes that I want to apply to this:

The only way I can think about doing it is:

{ user.safety_score > 0 ? "safety-bar active" : "safety-bar zero" }

However, If both if statements weren't a if else, I was wondering if there was any other shorthand that didn't involve creating an entire function that I could use.

Upvotes: 1

Views: 366

Answers (3)

dance2die
dance2die

Reputation: 36895

If you want to avoid if or ternary statements, you can take advantage of || operator.

How it works is that when user.safety_score isn't found in the flags, it will return undefined and the default value of active will be printed for all values other than 0.

let user = {
	safety_score: 0
}

const flags = ['zero']
// prints "safety-bar zero"
console.log(`safety-bar ${flags[user.safety_score] || 'active'}`);

user.safety_score = 3;
// prints "safety-bar active"
console.log(`safety-bar ${flags[user.safety_score] || 'active'}`);

Honestly,

{ user.safety_score > 0 ? "safety-bar active" : "safety-bar zero" }

looks good enough.

Upvotes: 2

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

<div className="{`safety-bar ${user.safety_score > 0 ? 'active' : 'zero'}`}"></div>

It uses the template string syntax to append the class using a conditional operator.

Upvotes: 4

Shamoon
Shamoon

Reputation: 43491

You can try:

render() {
  let safetyClass;
  if(user.safety_score > 0) {
   safetyClass = 'active'
  }

  if(user.safety_score === 0) {
   safetyClass = 'zero'
  }



  return <div className={`safety-bar ${safetyClass}`}>
}

Readable code is FAR better than shorthand.

Upvotes: 2

Related Questions