Skip to content
Related Articles

Related Articles

How to pass data from child component to its parent in ReactJS ?
  • Last Updated : 22 Feb, 2021

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
Recommended Articles
Page :