reactjs – Communication Between Components – Child to Parent Components

Sending data back to the parent, to do this we simply pass a function as a prop from the parent component to the child component, and the child component calls that function.

In this example, we will change the Parent state by passing a function to the Child component and invoking that function inside the Child component.

import React from 'react';

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };

        this.outputEvent = this.outputEvent.bind(this);
    }
    outputEvent(event) {
        // the event context comes from the Child
        this.setState({ count: this.state.count++ });
    }

    render() {
        const variable = 5;
        return (
            <div>
                Count: { this.state.count }
                <Child clickHandler={this.outputEvent} />
            </div>
        );
    }
}

class Child extends React.Component {
    render() {
        return (
            <button onClick={this.props.clickHandler}>
                Add One More
            </button>
        );
    }
}

export default Parent;

Note that the Parent’s outputEvent method (that changes the Parent state) is invoked by the Child’s button onClick event.

if you want to reproduce, please indicate the source:
reactjs – Communication Between Components – Child to Parent Components - CodeDay