Passing Data from Child to Parent Component in React JS using Hooks
Sridhar Raj P
?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ?? | JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver
Passing Data from Child to Parent Component in React JS using Hooks
In React, data flows from parent to child via props, but if you need to send data from child to parent, you can do so by passing a function as a prop from the parent to the child. The child component calls this function with the data, and the parent component updates its state.
Example: Sending Data from Child to Parent
1. Parent Component (Parent.jsx)
import React, { useState } from "react";
import Child from "./Child";
function Parent() {
const [data, setData] = useState("");
// Function to receive data from Child
const handleDataFromChild = (childData) => {
setData(childData);
};
return (
<div>
<h2>Parent Component</h2>
<p>Data from Child: {data}</p>
<Child sendDataToParent={handleDataFromChild} />
</div>
);
}
export default Parent;
2. Child Component (Child.jsx)
import React from "react";
function Child({ sendDataToParent }) {
const sendData = () => {
sendDataToParent("Hello from Child!");
};
return (
<div>
<h3>Child Component</h3>
<button onClick={sendData}>Send Data to Parent</button>
</div>
);
}
export default Child;
3. Use Parent Component in App.js
import React from "react";
import Parent from "./Parent";
function App() {
return (
<div>
<h1>Child to Parent Data Passing</h1>
<Parent />
</div>
);
}
export default App;
How It Works
Parent Component (Parent.jsx)
Child Component (Child.jsx)
App Component (App.js)