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.
1. Firstly, to make sure that we will start from the same point, you should create a brand new React project:
npx create-react-app example
2. Create a new file and call it Child.js inside the src directory (the name is totally up to you):
// src/Child.js
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;
3. Here’s the code for App.js (the parent):
// src/App.js
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 style={{padding: 30}}>
<Child passData={passData} />
<h4>The person info from the Child compoent:</h4>
<p>Name: <strong>{childData.name}</strong></p>
<p>Age: <strong>{childData.age}</strong> years old</p>
</div>
);
}
export default App;
4. Run it:
npm start
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:
- React: Show Image Preview before Uploading
- React: “I agree to terms” checkbox example
- React: Using inline styles with the calc() function
- React + TypeScript: Making a Custom Context Menu
- React + TypeScript: Create an Autosize Textarea from scratch
- React + TypeScript: Re-render a Component on Window Resize
You can also check our React topic page and React Native topic page for the latest tutorials and examples.