Dev

By Carlos Santana on
Reading time: 3 minutes

Binding-EzUQR.png

In this post, we are going to learn the two ways of binding methods in React: by using the class constructor and using arrow functions.

Class constructor binding

To explain this I'll create a basic Calculator component with only two inputs for the numbers and one button to see the result.

import React, { Component } from 'react';
import './Calculator.css';

class Calculator extends Component {
  constructor() {
    super();

    this.state = {
      number1: 0,
      number2: 0,
      result: 0
    };
  }

  render() {
    return (
      <div className="Calculator">
        <input name="number1" type="text" value={this.state.number1} />
        {' + '}
        <input name="number2" type="text" value={this.state.number2} />

        <p>
          <button>Result</button>
        </p>

        <p className="result">{this.state.result}</p>
      </div>
    );
  }
}

export default Calculator;
File: src/components/Calculator/Calculator.js

Now we need to add two new methods: one to handle the inputs (onChange event) and the other to manage the result button (onClick). We can use the same handleOnChange method for both inputs. Since we have the names of the fields (which are the same as the state) we can dynamically update each state, and in the handleResult method, we just sum both numbers: 

handleOnChange(e) {
  const { target: { value, name } } = e;

  this.setState({
    [name]: Number(value)
  });
}

handleResult(e) {
  this.setState({
    result: this.state.number1 + this.state.number2
  });
}

Now in our render method, we have to add the events to the inputs and the result button:

render() {
  return (
    <div className="Calculator">
      <input
        onChange={this.handleOnChange}
        name="number1"
        type="text"
        value={this.state.number1}
      />
      {' + '}
      <input
        onChange={this.handleOnChange}
        name="number2"
        type="text"
        value={this.state.number2}
      />

      <p>
        <button onClick={this.handleResult}>Result</button>
      </p>

      <p className="result">{this.state.result}</p>
    </div>
  );
}

This is the CSS for our calculator:

.Calculator {
  margin: 0 auto;
  padding: 50px;
}

.Calculator input {
  border: 1px solid #eee;
  font-size: 16px;
  text-align: center;
  height: 50px;
  width: 100px;
}

.Calculator button {
  background: #0072ff;
  border: none;
  color: #fff;
  font-size: 16px;
  height: 54px;
  width: 150px;
}

.Calculator .result {
  border: 10px solid red;
  background: #eee;
  margin: 0 auto;
  font-size: 24px;
  line-height: 100px;
  height: 100px;
  width: 100px;
}
File: src/components/Calculator/Calculator.css

If you run the application right now, you will see that if you try to write anything in the inputs or click on the button, you will get this error:

SetStateError-2GIAX.png

This is because we need to bind those methods to the class in order to have access to them in the render method. Let's bind our methods first by using the constructor: 

constructor() {
  super();

  this.state = {
    number1: 0,
    number2: 0,
    result: 0
  };

  // Binding methods
  this.handleOnChange = this.handleOnChange.bind(this); 
  this.handleResult = this.handleResult.bind(this);
}

Using the constructor to bind the methods is good if you want to list all the methods on the top of the component. If you run again the calculator now should work:

Calculator-gz1kB.png

Arrow function binding

Now let's use an arrow function to automatically bind our methods instead of doing it on the constructor. For this, you need to remove your bindings methods in the constructor and change the handleOnChange and handleResult methods to arrow functions like this:

Only members can see all the codes
You can Login or Sign Up

You will get the exact same result. Personally, I prefer to use arrow functions to bind methods because you use less code and you don't need to add the methods to the constructor manually.

As you can see, you have two options to bind methods in your React components. The constructor option is most commonly used at the moment, but the arrow functions are getting more popular. You decide which binding way you like the most.

If you have any question on React or any other technology feel free to join our Slack community.

avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up