Sometimes in our React app, we’ve to send data from a child component to its parent component.
In this article, we’ll look at how to send data from a child React component to its parent.
Pass a Function to the Child Component
To pass data from a parent component to the child, we can pass a function to a child component as a prop.
For instance, we can write:
import React, { useState } from "react";
const Counter = ({ parentCallback }) => {
const [count, setCount] = useState(0);
return (
<button
onClick={() => {
const newValue = count + 1;
setCount(newValue);
parentCallback(newValue);
}}
>
Click me {count}
</button>
);
};
export default function App() {
const callback = (val) => {
console.log(val);
};
return (
<div>
<Counter parentCallback={callback} />
</div>
);
}
We have the Counter
component that takes the parentCallback
prop.
In the component, we have the count
state created from the useState
hook.
Then we have a button with the onClick
callback that calls the parentCallback
with newValue
.
In the App
component, we have the callback
function that we pass into the Counter
component as the value of the parentCallback
prop.
Now when we click on the Click me button, we should see the console.log
function run with val
being the value we pass into parentCallback
in Counter
.
Conclusion
We can send data from a child React component to the parent component by passing in a function from the parent to the child.
Then in the child component, we can call it with the arguments we want to pass the argument values back to the parent component.