In React, data flows one-way (parent → child) by default. To pass data from child to parent, you use a callback function.
🔹 Steps to Pass Data from Child to Parent:
- Define a function in the parent to handle the data.
- Pass that function to the child via props.
- Call the function in the child, passing the data as an argument.
🔸 Example
✅ Parent Component:
import React, { useState } from 'react';
import Child from './Child';
function Parent() {
const [message, setMessage] = useState('');
const handleData = (dataFromChild) => {
setMessage(dataFromChild);
};
return (
<div>
<h2>Parent Component</h2>
<p>Message from Child: {message}</p>
<Child sendData={handleData} />
</div>
);
}
export default Parent;
✅ Child Component:
function Child({ sendData }) {
const handleClick = () => {
sendData("Hello from Child!");
};
return (
<div>
<h3>Child Component</h3>
<button onClick={handleClick}>Send Data to Parent</button>
</div>
);
}
export default Child;
✅ Output Behavior:
- When the button is clicked in the Child, it sends
"Hello from Child!"to the Parent, and the Parent displays it.
📌 Summary:
- Use callback functions passed as props to send data from child to parent.
- This is part of React’s “lifting state up” pattern.