Home > Enterprise >  Used a state inside of another state but updating it doesn't update the outer state, ReactJS
Used a state inside of another state but updating it doesn't update the outer state, ReactJS

Time:11-24

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 ?

CodePudding user response:

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

CodePudding user response:

try use callback

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