Passing Data from a Child Component to the Parent in React

Last updated on January 25, 2022 A Goodman Loading... Post a comment

In React, passing data from a parent component into a child component is quite easy with “props”. On the other hand, passing data from a child component to a parent component is a little more complicated and you will understand it better with the example below.

The Example

For small and simple applications, the easiest technique is to pass a function from the parent down to the child. This function can return something and we will retrieve it within the parent component.

Create a new file and called it Child.js inside the src directory (the name is totally up to you):

import React from 'react';

const Child = props => {
    const person = {
        name: 'John Doe',
        age: 999
    };

    const buttonClickHandler = () => {
        props.passData(person);
    }
    
    return <div>
        <button onClick={buttonClickHandler}>Show the info</button>
    </div>
}

export default Child;

App.js (the parent):

import React, { useState } from 'react';
import Child from './Child';

function App() {
  const [childData, setChildData] = useState({
    name: 'unknown',
    age: 'unknown'
  });

  const passData = (data) => {
    setChildData(data);
  };

  return (
    <div className="App">
      <Child passData={passData} />
      <p>The person info from the Child compoent: <strong>{childData.name}</strong>, <strong>{childData.age}</strong> years old</p>
    </div>
  );
}

export default App;

Check the result:

For more complex applications, you should use one wide state management solution, such as context, Redux, Mobx, etc.

Final Words

You’ve learned the easiest and quickest way to pass information from a child component to its parent in React. If you’d like to explore more new and interesting things about modern frontend development, take a look at the following articles:

You can also check our React topic page and React Native topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles