DEV Community

Muhammad Awais
Muhammad Awais

Posted on

How to share and change state between components using props

I have stuck at the point, where I want to get the state of toggle button in child component and also change that state from another child component, so I came up with the solution:

1. In your higher-order component initialize the state and the toggleHandler like below:

this.state = {
  headerToggle: true
}
Enter fullscreen mode Exit fullscreen mode
toggleHeader = () => {
  console.log("TOGGLE HEADER >", this.state.headerToggle)
  if (this.state.headerToggle) this.setState({ headerToggle: false});
  if (!this.state.headerToggle) this.setState({ headerToggle: true})
}
Enter fullscreen mode Exit fullscreen mode

2. pass the state and toggleHandler as props to a child component

<Header headerToggleHandler={this.toggleHeader} headerToggle={this.state.headerToggle} />
<BodyComp headerToggle={this.state.headerToggle} />
Enter fullscreen mode Exit fullscreen mode

3. get the props in a child component

const { headerToggleHandler, headerToggle } = props;
Enter fullscreen mode Exit fullscreen mode

4. toggling the state from child component

<IconButton onClick={handleDrawerToggle}>
  Menu toggle {headerToggle}
</IconButton>
Enter fullscreen mode Exit fullscreen mode
const handleDrawerToggle = () => {
  headerToggleHandler();
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
muhammadawaisshaikh profile image
Muhammad Awais