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
state
created withuseState
hook, managed withupdateState
function, - Child - which renders a
button
element that calls Parent'supdateState
method 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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
4
const Parent = () => {
5
const [state, setState] = React.useState(0);
6
7
const updateState = () => {
8
setState((state) => state + 1);
9
};
10
return (
11
<div>
12
<div>Parent's state: {state}</div>
13
<Child handler={updateState} />
14
</div>
15
);
16
};
17
18
const Child = (props) => {
19
return (
20
<div>
21
<button onClick={props.handler}>Update</button>
22
</div>
23
);
24
};
25
26
const root = document.querySelector('#root');
27
ReactDOM.render(<Parent />, root );