Talking to a parent component
We've learned earlier that a parent passes data to a child component by props. What about passing data from a child to a parent? The simplest way for child to talk to a parent is to call a function given from that parent:
1
type CounterProps = { increment: () => void; decrement: () => void; }
2
3
const Counter: React.FC<CounterProps> = ({ increment, decrement }) => {
4
return (
5
<div>
6
<button onClick={increment}>+</button>
7
<button onClick={decrement}>-</button>
8
</div>
9
)
10
}
Copied!
1
const App: React.FC = () => {
2
const [count, setCount] = useState<number>(0)
3
4
const onIncrement = () => setCount(count + 1)
5
const onDecrement = () => setCount(count - 1)
6
7
return (
8
<div>
9
{ count }
10
<Counter increment={onIncrement} decrement={onDecrement} />
11
</div>
12
)
13
}
Copied!
Copy link