Home > Software engineering >  Short-circuit expressions to dynamically add classes and/or other attributes
Short-circuit expressions to dynamically add classes and/or other attributes

Time:11-09

In a tutorial I'm following, I saw an interesting use of a template literal to apply classes dynamically.

The relevant JSX looks like:

<button
  key={job.id} 
  className={`job-btn ${index === i && "active-btn"}`} 
  onClick={() => setIndex(i)}
>
  {job.company}
</button>

The short-circuit && evaluation causes "active-btn" to only be applied when the index of the job (i) matches the state value index. A side effect of this is that if the expression evaluates to false, meaning if the index (i) of the job is not the state value index, then the boolean value false will be coerced to a string, attached as a class, and targetable with the .false selector. So the non-active buttons can be selected with the .false selector.

Is this a big deal, or is it accepted as a reasonable way to do things? If it's not ideal, is there a different way to achieve this dynamic adding of classes without this side effect? Thanks.

Maybe it's a silly question. The simple solution is just to avoid using .false to style things, but I thought I'd ask since I'm new to React.

Edit: One way I was made aware of is to use ${index === i ? "active-btn" : ""} This seems better.

CodePudding user response:

If you don't have any class false then it would be fine. But I won't recommend that

Live Demo

Codesandbox Demo

You can easily mitigate this problem using ternary operator. If index === i then there will be active-btn else there will not be any class added to the button.

className={`job-btn ${index === i ? "active-btn" : ""}`}
  • Related