Send information from Child to Parent - Callbacks in react

sabrinasuarezarrieta

sabrinasuarezarrieta

Posted on November 28, 2020

Send information from Child to Parent - Callbacks in react

Passing data between components of different levels is important and also a trickier thing to do in Reactjs. The data flow from parent to child is easier and really straight forward, is just about using the props but from child to parent can be a little bit trickier and I see how can confuse some developers.

The first thing you have to do is create a callback function in the Parent to take in the parameter that you have accessed from the child and send the callback function to the Child as a prop.

import React, { useState, Component} from 'react';
import ChildComponent from './child-component/child-component'

class Parent extends Component {

constructor(props) {
        super(props);
        this.state = {
            message: ''
        };
    }

modifyMessage= (data) => {
      this.setState({message: data})
},

 render() {
        return (
            <div>
                 <ChildComponent parentCallback = {this.modifyMessage}/>
                 <h1> {this.state.message} </h1>
            </div>
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

After doing this, in the Child we need to pass the data using this.props.callback(dataToParent), in this case, the event is sent at the click of the button in the page.

import React, { Component} from 'react';

class Child extends Component {

constructor(props) {
        super(props);
    }

handleClick = (e) => {
    this.props.parentCallback('wow you click the child component');
};

 render() {
        return (
            <div>
                 <button onClick={this.handleClick}>Click this child!</button>
            </div>
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

When the button of Child is clicked, it triggered the ‘modifyMessage’ in Parent and set the message as “wow you click the child component”. We set in the state because if we do not do it like that we could not be able to use the data outside the function.

I hope this example will be useful for all of you, Thank you very much for reading and I wish you a nice day!!

💖 💪 🙅 🚩
sabrinasuarezarrieta
sabrinasuarezarrieta

Posted on November 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related