Passing data from a child component to a parent component in React

February 17, 2020 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.

Create a new file and called it Child.js (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;

Now run your code and check the result after clicking the button. The name and the age will change from “unknown” to “John Doe” and “999” 🙂

guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x