Passing data from child to parent component in ReactJS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Passing data from child to parent component in ReactJS #

To pass data from child to parent component in React:

  1. Pass a function as a prop to the Child component.
  2. Call the function in the Child component and pass the data as arguments.
  3. Access the data in the function in the Parent.
App.js
import {useState} from 'react'; function Child({handleClick}) { return ( <div> <button onClick={event => handleClick(100)}>Click</button> </div> ); } export default function Parent() { const [count, setCount] = useState(0); const handleClick = num => { // 👇️ take parameter passed from Child component setCount(current => current + num); }; return ( <div> <Child handleClick={handleClick} /> <h2>Count: {count}</h2> </div> ); }

pass data from child to parent

The Parent component defines a handleClick function that takes a num argument.

We passed the function as a prop to the Child component, so the Child is able to call the function and pass it any data we need to access in the Parent.

When the button element of the Child is clicked, the handleClick function is invoked and the argument we pass to the function can be accessed in the Parent component.

You might also need to include the event object in the function's parameters.

App.js
import {useState} from 'react'; function Child({handleClick}) { return ( <div> <button onClick={event => handleClick(event, 100)}> Click </button> </div> ); } export default function Parent() { const [count, setCount] = useState(0); const handleClick = (event, num) => { console.log(event.target); setCount(current => current + num); }; return ( <div> <Child handleClick={handleClick} /> <h2>Count: {count}</h2> </div> ); }

Now the handleClick function takes the event object and a number as parameters and the Child component forwards the event to the Parent.

You can use this approach to pass anything from a Child to a Parent component.

All we have to do is pass a function prop to the Child and call the function in the Child component, passing it the data we need to access in the Parent as arguments.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.