Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!