React.js: Communication between Components

FrontEnd Reading Time: 2 min.

  • views2179
  • 0comments
Share

In React, communication between the components proceeds in a hierarchical way. This means that by default we only have the possibility to pass data from parent component to children component using props attribute and not the opposite. It’s not any kind of a “bug” or a disadvantage, but a deliberate construction which should help us design application architecture in a clearer and easier way to understand it. In practice this approach is not always satisfying, and even our workflow is in line with all the best practice we need sometimes change parent component state by his children. Fortunately, there are a few solutions to that. One of the simplest methods to achieve it is through callbacks passed by a parent component as a prop.

Let’s check it in practice.

In a simple example below we have two components: parent – Header and child – Button. Parent component has defined the following functions:

  • showHeader() – a function depends on the state of the headerMsg return header message or not.
  • changeHeaderState() – a function that modified the state of the component.
import React, { Component } from 'react';
import Button from './button';

export default class Header extends Component {

  constructor() {
    super();
    this.state = {
        headerMsg: true
    }
  }

  changeHeaderState() {
      if (this.state.headerMsg) {
          this.setState({headerMsg: false})
      } else {
          this.setState({headerMsg: true})
      }
  }

  showHeader(){
      if(this.state.headerMsg) {
          return (
              <h1> Header message </h1>
          );
      }
  }

  render() {
    return(
        <div>
            {this.showHeader()}
            <Button showHeader={this.changeHeaderState.bind(this)}/>
        </div>
    );
  }
}

In Button component, we have implemented a handleClick() method which executes our callback function passed by props. In this case, when the user clicks on a button, a callback showHeader() is executed and the state of parent component is changed.

import React, { Component } from 'react';

export default class Button extends Component {
    constructor() {
        super();
    }

    handleClick() {
        this.props.showHeader(); // execute callback passed over props.
    }

    render() {
        return(
            <div>
                <button onClick={this.handleClick.bind(this)}> Example </button>
            </div>
        );
    }
}

Button.propTypes = {
    showHeader: React.PropTypes.func
};

And in this simple way we solve our problem. The result of our work is below.


React

Tagged with:

Tags: ,