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

313
Visualizações
How to target DOM and change style in react with mapped elements

I have a multi page form that renders a list of buttons for each possible answer.

I am currently using getElementByID to change the button style when a button is clicked. I think this is not considered good practice in react.

can I use the useRef hook to target the DOM element and change its style instead of using getElementByID if the buttons are dynamically displayed with map?

{answers.map((answer, count = 0) => {
        return (
          <Button
            key={count}
            id=`button${count}`
            onClick={(e) => {        
              document.getElementById(`${e.currentTarget.id}`).style.color = "white";
            }}
          >
            <ButtonTitle>{answer.name}</ButtonTitle>
          </Button>
        );
      })}

(animations on safari are breaking the active style, so I can't use the active pseudo element)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do this by adding a new state and toggle active class by that state. Code something like this.

const [activeindex, setActiveIndex] = useState("");

return(
<>
{answers.map((answer, count = 0) => {
        return (
          <Button
            key={count}
            className={count==activeindex?"acvie":""}
            onClick={(e) => {        
              setActiveIndex(count)
            }}
          >
            <ButtonTitle>{answer.name}</ButtonTitle>
          </Button>
        );
      })}
}
</>

And use .active class in css file.

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