EN
React - update parent's state
0
points
In this article, we would like to show you how to update parent's state in React.
Below we create two React components:
- Parent - which has a
statecreated withuseStatehook, managed withupdateStatefunction, - Child - which renders a
buttonelement that calls Parent'supdateStatemethod on click event.
Inside Parent, we render the Child component to which we pass updateState function as a handler property.
Child component receives handler via props and uses props.handler inside onClick property to update Parent's state when the onClick event occurs.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
const Parent = () => {
const [state, setState] = React.useState(0);
const updateState = () => {
setState((state) => state + 1);
};
return (
<div>
<div>Parent's state: {state}</div>
<Child handler={updateState} />
</div>
);
};
const Child = (props) => {
return (
<div>
<button onClick={props.handler}>Update</button>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Parent />, root );