How to bind React component event handlers in ES6

When creating React components using ES6 class notation, you'll need to bind event handlers passed as props to this, or you'll find that the handlers will be bound instead to the DOM element.

There are a few ways to do this. You can reassign the bound handler in the constructor:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.onClick.bind(this)}>Click Me</button>
      </div>
    );
  }

  onClick(event) {
    alert("You clicked me!");
  }
}

This works fine, but now you have .bind(this) littering your otherwise elegant JSX.

To remedy that, you can use the fat arrow prototype method syntax:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.onClick.bind(this)}>Click Me</button>
      </div>
    );
  }

  onClick = (event) => {
    alert("You clicked me!");
  }
}

Except... now you have two separate syntaxes for declaring methods, which could make your code less readable and more confusing.

I think the most elegant way is to use the new double-colon (::) notation, which is a shortcut for calling .bind(this) on a given handler:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={::this.onClick}>Click Me</button>
      </div>
    );
  }

  onClick(event) {
    alert("You clicked me!");
  }
}

Now your caller is binding the method to this without an ugly .bind(this) call, and the method body isn't unnecessarily decorated with fat arrow notation.

Building a new Digital Product? Read This First

You're about to build your first digital product, but you're terrified at the breadth of terminology and wary of consultants nickel-and-diming you.

My free book Why Software Projects Fail offers that framework. In this companion to your hiring and discovery process, you'll learn how to inform your next decisions and to empower yourself along the way.

In the book, you'll learn:

  • How to find and hire a trustworthy consultant
  • Why it's critical you pay for a software discovery
  • How to assess your consultant's bid
  • What to expect—and be wary of—during the development process
  • How to take control of your project

Enter your email address below and then click the "Send Me My Free Gift" button. I'll send you Why Software Projects Fail, and you'll be equipped for success on your next project.