How to Easily Pass Data From Child to Parent in React
To easily pass data from your child to the parent component in React, pass a callback function to your child as a prop, call the function inside your child with your data, and access the data within your function from your parent component. This looks like the following in terms of code:
import { useState } from 'react'
const Child = ({ callback }) => {
const state = {
example: 'π'
}
const handleCallback = () => callback(state)
return (
<button onClick={handleCallback}>Pass data to parent</button>
)
}
export default function Parent() {
const [state, setState] = useState({})
const callback = payload => {
setState(payload)
console.log(state)
}
return (
<div>
<h1>Hello from Parent</h1>
<Child callback={callback} />
</div>
)
}
First, we created an empty state inside the parent component using the useState
hook. Then we called the Child
component with a callback
prop, passing it a function that we defined inside our parent.
Notice that we use setState
to set the state to the payload of the function. This function will be called from within our Child
component, and it will be responsible for passing the correct data. Let's take a look at the child component now.
const Child = ({ callback }) => {
const state = {
example: 'π'
}
// Here we are setting the payload for the callback inside the Parent
const handleCallback = () => callback(state)
return (
<button onClick={handleCallback}>Pass data to parent</button>
)
}
Inside the child, we destructure the props so that we can grab callback
right away, then call it with the internal state using an onClick
handler. This state
object will be the value of the payload that we receive inside our Parent
component.
This way, you can pass any data you need from your Child
component to your Parent
using a callback function. And by using a useState
hook inside the parent, we can also access the passed state outside of the callback function.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: