Pass data from child component to its parent component in React Js
In this post, we will learn about how to pass data from child component to its parent component in React js.
We need to do following steps to pass/send data from child component to parent component:
a) In the parent component, create a callback function. This callback function is useful to retrieve the data from the child component.
b) Pass the callback function to the child as a props from the parent component.
c) The child component calls the parent callback function using props and sends the data to the parent component.
|
Send data from child component to its parent component |
Sample Code:
A) index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
B) App.js
import React, { useState } from 'react';
import './style.css';
const ChildComponent = (props) => {
const { parentCallBackFunction } = props;
const [firstN, setFirstN] = useState('');
const [lastN, setLastN] = useState('');
const onSubmitForm = (e) => {
parentCallBackFunction(firstN, lastN);
};
const onChangeFirstName = (e) => {
setFirstN(e.target.value);
};
const onChangeLastName = (e) => {
setLastN(e.target.value);
};
return (
<>
<div id="child">
<span>Child Component</span>
<div id="firstName">
<label>First Name </label>
<input
type="text"
name="firstname"
placeholder="Enter First Name"
onChange={onChangeFirstName}
/>{' '}
<br />
</div>
<div id="lastName">
<label>Last Name </label>
<input
type="text"
name="lastname"
placeholder="Enter Last Name"
onChange={onChangeLastName}
/>
</div>
<button id="submit" onClick={onSubmitForm}>
Submit values to Parent Component
</button>
</div>
</>
);
};
export default function App() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const handleCallbackFunction = (firstname, lastname) => {
setFirstName(firstname);
setLastName(lastname);
};
return (
<div id="parent">
<span>Parent Component</span>
<ChildComponent parentCallBackFunction={handleCallbackFunction} />
<label>First Name: {firstName}</label> <br />
<label>Last Name: {lastName}</label>
</div>
);
}
C) style.css
#parent {
border: 1px solid black;
width: 350px;
height: 250px;
margin: 5px;
padding: 5px;
background-color: orange;
font-weight: bold;
}
#child {
margin: 20px;
margin-left: 20px;
border: 1px solid black;
padding: 3px;
height: 145px;
width: 300px;
background-color: green;
}
#firstName {
margin: 20px;
}
#lastName {
margin: 20px;
}
#submit {
margin-left: 15px;
}
Happy Learning!! Happy Coding!!
Comments