Search code examples
javascripthtmlreactjssetstate

Change state of member variable in React not working


I have a class Box2 which I have made an instance of in Box1

Box1 just renders the instance which is has of Box2 however using setState for that instance that I have it doesnt change

import React from 'react';
import ReactDOM from 'react-dom';

class Box2 extends React.Component{
    constructor(props){
        super(props);
        this.state={text:"No"};
    }
    render(){
        return(
        <h1>
            {this.state.text}
        </h1>
        );
    }
}

export default class Box1 extends React.Component{
    Elements=[];
    constructor(){
        super();
        this.Elements[0]=new Box2();
        this.Elements[0].setState({text:"YES"});
    }
    render(){
        return(<div>
        {this.Elements.map((e)=>e.render())};
        </div>
        );
    }
}

Solution

  • You can not change state of your child components. Instead you should use props:

    class Box2 extends React.Component{
      render(){
        return(
          <h1 onClick={this.props.onClick}>
            {this.props.text}
          </h1>
        );
      }
    }
    
    export default class Box1 extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          isBox2Yes: true,
        };
    
        this.onBoxClick = this.onBoxClick.bind(this);
      }
    
      onBoxClick() {
        this.setState({ isBox2Yes: !this.state.isBox2Yes });
      }
    
      render(){
        return(
          <div>
            <Box2
              text={this.state.isBox2Yes ? 'YES' : 'NO'}
              onClick={this.onBoxClick}
            />
          </div>
        );
      }
    }