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

122
Vistas
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 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