Table of Contents

Passing Value, Reference Between Components

In this example, we will show how to pass value, reference between components. We will have an outter container component MyContainer, and within that component we will have 3 inner components InnerComponent that contain a button each to change a value in the container component.

InnerComponent

InnerComponent contains a button. It receives a function callback and a value through the props. While the button is clicked, it calls onButtonClickHandler which we will pass it from the MyContainer Component. onButtonClickHandler is binded to updateValueHandler method in the MyContainer component, and we will see it later. We can use such method to pass value back to the container component.

import React from "react";

const InnerComponent = (props) => {
    return (
        <div>
            <button onClick={props.onButtonClickHandler.bind(this, props.value)}>Chang value to {props.value} </button>
        </div>
    )
};

export default InnerComponent;

MyContainer Component

My container has an internal state storing a value, a label display that value, and three InnerComponents. For setting up each InnerComponent, we set the props by putting key-value pairs inside tag. We can access those by props.value, and props.onButtonClickHandler inside InnerComponent. This is how we pass values to a child component. If we want to pass values from the same level component, we might need the help of their parents component.

import React, {Component} from "react";
import InnerComponent from "./InnerComponent";

class MyContainer extends Component {
    state = {
        value: 0
    };

    updateValueHandler = (newValue) => {
        this.setState((prevState, props) => {
            return {
                value: newValue
            }
        });
    };


    render() {
        return (
            <div>
                value = {this.state.value}
                <InnerComponent value={1} onButtonClickHandler={this.updateValueHandler}/>
                <InnerComponent value={2} onButtonClickHandler={this.updateValueHandler}/>
                <InnerComponent value={3} onButtonClickHandler={this.updateValueHandler}/>
            </div>
        )
    }
}

export default MyContainer;