torayeff torayeff - 3 months ago 13
Javascript Question

React js change child component's state from parent component

I have two components:
Parent Component from which I want to change child component's state:

class ParentComponent extends Component {
toggleChildMenu() {
?????????
}
render() {
return (
<div>
<button onClick={toggleChildMenu.bind(this)}>
Toggle Menu from Parent
</button>
<ChildComponent />
</div>
);
}
}


And Child Component:

class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false;
}
}

toggleMenu() {
this.setState({
open: !this.state.open
});
}

render() {
return (
<Drawer open={this.state.open}/>
);
}
}


I need to either change Child Component's open state from Parent Component, or call Child Component's toggleMenu() from Parent Component when Button in Parent Component is clicked?

Answer

the state should be managed in the parent component. You can transfer the open value to the child component by adding a property

class ParentComponent extends Component {
   constructor(props) {
      super(props);
      this.state = {
        open: false;
      }
   }

   toggleMenu() {
      this.setState({
        open: !this.state.open
      });
   }

   render() {
      return (
         <div>
           <button onClick={toggleChildMenu.bind(this)}>
              Toggle Menu from Parent
           </button>
           <ChildComponent open={this.state.open} />
         </div>
       );
    }
}

class ChildComponent extends Component {
    render() {
      return (
         <Drawer open={this.props.open}/>
      );
    }
}
Comments