DEV Community

Muhammad Awais
Muhammad Awais

Posted on

2 1

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

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (1)

Collapse
 
muhammadawaisshaikh profile image
Muhammad Awais

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay