Passing Usestate From Child Component To Parent Component?
I am trying to pass up the state 'region' defined in my useState Hook to the parent element. Im not sure where to put the word region in order to do that though? This is the Child
Solution 1:
Passing UseState from child component to parent component?
No you shouldn't. This is an anti-pattern of React's Data Flows Down.
If you want both the parent and child component make use of region
state, you should lift state up instead.
classParentextendsReact.Component {
constructor(props) {
super(props);
this.state = {
region: 'Africa'// region is owned by Parent component
}
}
// class field syntax
updateRegion = (region) => {
this.setState({ region });
}
render() {
// Pass region state down as prop// Also provide an updater function for setting region in child componentreturn (
<divid="search_dropdown"><MenuupdateRegion={this.updateRegion}region={this.state.region} /></div>
);
}
}
Post a Comment for "Passing Usestate From Child Component To Parent Component?"