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

178
Vistas
Used a state inside of another state but updating it doesn't update the outer state, ReactJS

I have a JSX element that I want to control its CSS class with a state, and the element itself is also nested in another state as below:

this.setState({
   content: <div className={this.state.cClass} />
})

The problem is, when I update the cClass state, I want the content state get updated as well but it stays the same. How can I solve this problem ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I have modified your code. once you return the content state it gets loaded into the DOM but after the setTimeout cClass state is updated but still it won't reflect in the DOM as class property is still "App" in the HTML DOM. which has no more reference to the this.state.cClass

import "./styles.css";
import React from "react";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cClass: "App"
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState(
        {
          cClass: "App fade"
        },
        () => {
          console.log(this.state.cClass);
        }
      );
    }, 2000);
  }

  render() {
    return (
      <div className={this.state.cClass}>
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

Edit naughty-sammet-l7zef

about 4 years ago · Juan Pablo Isaza Denunciar

0

try use callback

this.setState((prevState)=>({
   content: <div className={prevState.cClass} />
})

// edited lifecycle

componentDidUpdate(prevProps, prevState){
   if(prevState.cClass !== state.cClass){
       this.setState({
          content: <div className={prevState.cClass} />
       })
   }
}
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