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

125
Visualizações
instant html class change by DOM manipulation in React

In React app I have a code to toggle html element's (let's call it element A) class when pushing a button. I do it by mutating a state which contains settings for the whole app. Then when the element A is rendered it checks the appropriate setting and apply or not apply the class to it.

This works, but it takes a long time to re-render everything and thus there is a lag between click and changes applied. So I thought to use a little hack here with classic DOM manipulation to first change class (to see changes instantaneously) and then let React re-render everything.

The issue I have is that the changes are not applied by DOM manipulation, but only later after re-render. When I comment the setState line, the changes are visible immediately.

My question is, how to achieve instant class change and what could be wrong here?

  const handleCollapseToggle = (i, el) => { 
    const helpToggler = document.getElementById(el);
    helpToggler.classList.toggle('is-hidden');
    console.log('test',helpToggler);

    const newCollapsed = Array.from(settings.collapsed);           
    newCollapsed[i] = !newCollapsed[i];                             

    const newSettings = {
      ...settings, 
      collapsed:newCollapsed
    }    

    setSettings(newSettings);

    //setTimeout(setSettings(newSettings), 10000);
 }

I have also tried the setTimeout to apply a new state (please see on the last commented line of code), but that did not work and even did take less then 10 seconds to re-render. Also the console.log('test',helpToggler) logs out the 'test' word first and then the element itself later after re-render (on the same console log line).

about 4 years ago · Juan Pablo Isaza
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