Joelgullander
Joelgullander

Reputation: 1684

Conditional logic jsx react

I am trying to apply more than 1 condition to className in my jsx view. However it won't let me.

It only listens to the first condition.

className={usernameFocus ? "toggled" : "" || usernameValidated ? "validated" : ""}

I have tried several combinations:

className={usernameFocus ? "toggled" : "" + usernameValidated ? "validated" : ""}

How could I accomplish more than one conditional to add classNames to my element?

Upvotes: 2

Views: 233

Answers (2)

Mario Tacke
Mario Tacke

Reputation: 5488

Your order of operations is mixed up. Put your separate conditions in parentheses. Also, you can short-circuit the class evaluation like this:

className={(usernameFocus && "toggled") + " " + (usernameValidated && "validated")}

If you feel extra fancy, you can also use a template string:

className={`${usernameFocus && "toggled"} ${usernameValidated && "validated"}`}

If you do this a lot (multiple booleans), have a look at the officially recommended classnames module by Jed Watson. Link.

With it, you can do it like this:

var usernameClasses = classNames({
  'validated': usernameValidated,
  'toggled': usernameFocus
});

className={usernameClasses};

Upvotes: 2

Rob Brander
Rob Brander

Reputation: 3781

I think you are missing a space between the class names for when both are applied, also brackets help with multiple nested conditional statements.

Try this:

className={(usernameFocus ? "toggled" : "") + " " + (usernameValidated ? "validated" : "")}

Upvotes: 2

Related Questions