Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Short-circuit expressions to dynamically add classes and/or other attributes

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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" : ""}`}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading