React.js ES6 avoid binding ‘this’ to every method

You can use class fields to do the binding outside the constructor. They look like the following:

class Foo extends React.Component {

  handleBar = () => {
    console.log('neat');
  };

  handleFoo = () => {
    console.log('cool');
  };

  render() {
    return (
      <div
        onClick={this.handleBar}
        onMouseOver={this.handleFoo}
      />
    );
  }

}

Class fields are supported experimentally by Babel via its class properties transform, but they are still “experimental” because they are a Stage 3 Draft (not yet in a Babel preset).

You will need to do the binding manually until ES7 or until enabling the feature in Babel, however. This topic is covered briefly in Babel’s blog post on React on ES6+.

Leave a Comment