Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda