How To Pass Data From Child To Parent Component In React

Introduction

In this article, we will see how to pass data from the child component to the parent component in react. Sometimes we have a requirement where we want data from the child to the parent component.

In this series, we are learning about basic react js concepts. This article is about how to pass data from the child component to the parent component in react.  In the previous article, we learned how to use react table and sort the column in the table.

Let's create one component with the name ChildComponent.js. We are using one const variable to increase the plus 1 value when we click on the and call the props function. 

 ChildComponent.js

import React,{useState} from "react";

function ChildComponent(props){
    const [count,setCount]  = useState(0);

    const counter =()=>{
      setCount(count + 1);
      return count
    }
 
    return (
    <div className="div-child">
    <h1>This is Child Component  </h1> 
    <button onClick={()=>props.sendToParent(counter())} >Click me</button>   
    </div>
 )
}
export default ChildComponent;

Now we have just imported the child component and created one function to get the value from the child component and set it into one state then show that value on the parent component.

App.js

import { useState } from 'react';
import './App.css';
import Child from './ChildComponent';

function App() {
  
  const[ChildValue,SetChildValue] = useState()
  const getChildData=(val) =>{    
    console.log(val)
    SetChildValue(val)
  }

  return (
    <div className="App"> 
    <div className='div-parent'>
    <h1> This is Parent Component - {ChildValue} </h1>
    </div>   
     <Child sendToParent={getChildData} /> 
    </div>
  );
}
export default App;

We have added some CSS for styling to display both components clearly in the App CSS file.

App.css

.div-parent{
  height: 150px;
  width: 600px;  
  margin-left: 30%;
  margin-top: 5%;
  background-color: yellow;
  border: solid;
}

.div-child{
  height: 150px;
  width: 600px;  
  margin-left: 30%;
  margin-top: 5%;
  background-color: skyblue;
  border: solid;
}

Now just run the application with the npm start command and open the application. We can see the below output for passing data from the child to the parent component. Once you click on the button in the child component and that value we can able to access the parent component. 

How To Pass Data From Child To Parent Component In React

Summary

In this article, we have learned how to pass data from the child component to the parent component in react. This concept also knows as Lifting state up in react. I hope you understand this concept. Thank you for reading this article.