Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
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.

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" : ""}`}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!