How to pass data from child component to its parent in ReactJS
Codamint
Posted on April 27, 2024
Lifting the state up is the process by which React passes data from child to parent components. Following are the steps to pass data from the child component to the parent component:
- Define State in Parent Component: Specify the state that you like to be updated in the parent component in response to an action taken by the child component.
- Callback Function Pass Down: As a prop, a callback function is sent down from the parent component to the child component.
- Callback Invocation in Child Component: In the child component, call the callback function that was sent down from the parent component with the appropriate data to be delivered in response to the desired action (such as a button click).
Here's a simple example to help you understand this:
ParentComponent.js:
import { useState } from 'react';
import ChildComponent from './Child';
const ParentComponent = () => {
const [dataFromChild, setDataFromChild] = useState('');
const handleDataFromChild = (data) => {
setDataFromChild(data);
};
return (
<div>
<h1>Data from Child: {dataFromChild}</h1>
<ChildComponent sendDataToParent={handleDataFromChild} />
</div>
);
};
export default ParentComponent;
ChildComponent.js:
const ChildComponent = ({ sendDataToParent }) => {
const sendData = () => {
const data = 'Data sent from child';
sendDataToParent(data);
};
return (
<div>
<button onClick={sendData}>Send Data to Parent</button>
</div>
);
};
export default ChildComponent;
In this case, clicking the button in the ChildComponent initiates the sendData method, which in turn calls the sendDataToParent callback function, which receives the data you wish to transfer ('Data sent from kid') from the parent component. Following that, the handleDataFromChild function within the parent component is called for, As a result updating the state with the data obtained from the child component.
Posted on April 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.