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

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

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 Relatório

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