The Wayback Machine - https://web.archive.org/web/20230518180153/https://www.geeksforgeeks.org/how-to-pass-data-from-child-component-to-its-parent-in-reactjs/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to pass data from child component to its parent in ReactJS ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Following are the steps to pass data from child component to parent component:

  • In the parent component, create a callback function. This callback function will retrieve the data from the child component.
  • Pass the callback function to the child as a props from the parent component.
  • The child component calls the parent callback function using props and passes the data to the parent component.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Filepath- src/App.js:

Javascript




import React from 'react';
import Child from './Child'
class App extends React.Component{
      
       state = {
        name: "",
       }
  
    handleCallback = (childData) =>{
        this.setState({name: childData})
    }
  
    render(){
        const {name} = this.state;
        return(
            <div>
                <Child parentCallback = {this.handleCallback}/>
                {name}
            </div>
        )
    }
}
export default App

Filepath- src/component/Child.js

Javascript




import React from 'react'
class Child extends React.Component{
    
    onTrigger = (event) => {
        this.props.parentCallback(event.target.myname.value);
        event.preventDefault();
    }
  
    render(){
        return(
        <div>
            <form onSubmit = {this.onTrigger}>
                <input type = "text" 
                name = "myname" placeholder = "Enter Name"/>
                <br></br><br></br>
                <input type = "submit" value = "Submit"/>
                <br></br><br></br>
            </form>
        </div>
        )
    }
}
export default Child

Output:


My Personal Notes arrow_drop_up
Last Updated : 22 Feb, 2021
Like Article
Save Article
Similar Reads
Related Tutorials