Passing data from child to parent component in ReactJS

avatar

Borislav Hadzhiev

Sun May 01 20222 min read

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 parameter.

We passed the function as a prop to the Child component, so it 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 parameter we pass to the function can be accessed in the Parent component.

You might also need to take the event object as a parameter.

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 the Child to the 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.