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

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (1)

Collapse
 
muhammadawaisshaikh profile image
Muhammad Awais

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay