Codehiker Codehiker - 6 months ago 86
React JSX Question

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?


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