Last updated on May 21, 2021 by Suraj Sharma
In this tutorial, you'll learn how you can pass data up from a child component to its parent component in React.
Suppose you have a function component <Parent />
and a child component <Child />
rendered inside the <Parent />
.
Parent.tsx
import React from 'react';
const Parent: React.FC = () => {
const [label, updateLabel] = React.useState('');
return (
<>
<p>{label}</p>
<Child />
</>
)
}
Child.tsx
import React from 'react';
const Child: React.FC = ({ updateLabel }) => {
return (
<input onChange={(event)=>updateLabel(event.target.value)} />
)
};
When we type something down in the <input />
field in the <Child />
, the input field's change
event get fired, which is turn calls the updateLabel()
method passed down to the <Child />
from the <Parent />
as a props
To achieve this we have to pass the label
setter function as one of the props to the <Child />
.
Here, I have added a updateLabel
property to the updateLabel()
method from the <Parent />
component
Parent.tsx
<Child updateLabel={updateLabel} />
Related Solutions
Call parent component method in a child component in React and Typescript
How to pass props to the makeStyles API in React Material UI
Rate this post
Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.