Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda