React use case: reset state of the child function component from the parent component
A very simple use case in React, but I didn’t find any article that gives a clean answer — maybe I didn’t read enough.
Here is the situation:
- You have a big form to implement. You put the different sections of the form into different React function components.
- The form, hence, the parent component has many child components.
- The function components use the state hook to manage the state in the component and pass the state back to the parent component.
- In the parent component, there is a Reset button.
Here is what you expect:
- After clicking the Reset button, you want to clear the state in all the function components.
Here is the reality:
- Your child component state is not cleared
Here is the solution:
- In the child function component, you add a clearState function.
- You pass the clearState function from the child component to the parent by using one of the props function.
- In the resetForm of parent component, call the clearState function to clear child state.
Let’s code, shall we…
In your function component:
...(props) { [email, setEmail] = useState('');
// this method clear the state in child component
clearState = () => {
setEmail('');
} // pass the clearState function back to parent
props.passClearStateFunc(clearState); // many codes not relative to this topic, including pass state
// back etc... too much that I don't even want to know
...}
In your parent component (assuming the parent is a class component. Code could be applied to function component with minor changes):
//this is the reference to the child clearState function
clearChildState = null;// this method assigns the child clearState function
// to the parent reference
assignClearChildState(childClearStateFunc) {
this.clearChildState = childClearStateFunc;
}// this method gets the child state for completeness of
// the childComp tag
getStateCallback(email) {
//do something to use the child state
}resetForm() {
this.clearChildState();
}...
// this passes the assignClearChildState function
// from parent to child so the child can use it
// to pass the clearState back
<ChildComp getState={getStateCallback} passClearStateFunc={assignClearChildState} /> <button type="reset" onclick={resetForm}>
Reset
</button>
Hope I didn’t confuse you. You are not confused, right?