Children To Parent Component Communication In React

We all know that communication between components is quiet important in ReactJS. React’s one-way data flow keeps the application modular and fast. The normal react application consists of multiple components, and they could be nested as well. It is easy for a parent component to communicate with the child component, i.e using props or state passed as props to child component, but what if the child component communication with parent component? How does it happen? It happens using callbacks, in this post I will demonstrate a simple example.

Here is a Parent component:

import React from 'react';

import Child from './Child'

export default class Parent extends React.Component {

      constructor(props){

            super(props);

            this.state ={ text:''};

       }

     handleChangeInParent = (event) => {

             this.setState({text:event.target.value})

     }

    render() {

        return (

                  <>

                     <p>You have written: </p>

                     <p>{this.state.text}</p>

                     <Child handleChange={this.handleChangeInParent}/>

                   </>

                )

      }

}

Here is the Child component:

import React from 'react';

const Child = (props) => {

               return (
                      <div>

                        <inputtype="text"onChange={props.handleChange}/>

                      </div>
                   )
}

export default Child

Here what we see is that we have a Child component which we use in Parent component, both are very simple components. Child component has a text field but it is getting displayed in Parent component using a callback fuction, i.e handleChangeInParent. This function is being passed in as a prop to the Child component, i.e handleChange. When the onChange event inside the Child component is triggered it calls the props in Child and subsequently handleChangeInParent function receives the event value and sets it in the state. We could have directly passed the text value to Parent component as well, for that the Child should have been a stateful Component, and here it is stateless. I hope you get the picture of how to handle communication between child and parent in React.