Reputation: 1883
Let's say I have a component.
Inside that component I am calling a child component.
That child component has a state, which I would want to set from the parent component.
Component
// component
// ...
setState( 1 );
<ChildComponent ???setStateFunc={setState}???> // This setState should point to the child function
setState( 2 );
// ...
// end component
Child component
// child component
// ...
const [state, setState] = useState(null);
// ...
// end child component
How do I do that?
Upvotes: 0
Views: 81
Reputation: 1210
If you want your Parent Component State should update from Child Component, handle your states like this:
Add this to your Parent Component File:
this.state = {
value: 0
}
...
changeHandler = (e) => {
this.setState({value: e})
}
...
//Pass this function like this
<ChildComponent value={{this.state.value}} setValue={(e) => changeHandler(e)}>
And manage your setValue by setting any value from your Child Component file, like:
...
//For example if you're using TextInput component
<TextInput
value={this.props.value}
onChangeText={this.props.setValue}
/>
...
Hope this works for you.
Upvotes: 1