.bind(this) no more!

If you’re working on a React/React Native project you’ve probably had to deal with binding event handlers.
It isn’t a React specific issue, but a part of the way functions work in JavaScript.

Manually binding each component method may sound considerable. This is the “old school” way - bind in constructor():

this.handleClick = this.handleClick.bind(this);

But believe me when I tell you, repeating it for 5+ methods is both annoying and quite ugly:

this.addComment = this.addComment.bind(this)
this.removeComment = this.removeComment.bind(this)
this.editComment = this.editComment.bind(this)
this.fetchComments = this.fetchComments.bind(this)
this.clapComment = this.clapComment.bind(this)
this.bookmarkComment = this.bookmarkComment.bind(this)

Nasty gif

While I’m a big fan of arrow function expressions and the public class field feature, which uses the first to solve the problem (“Lexical Scoping”), it is still experimental and not yet part of ECMAScript standard (stage 3).

Solution - Autobinding Packages

There are 3 packages I came across:

  1. Autobind Decorator - Coming from Python, the decorators pattern of adding @autobind before methods seemed almost natural.
    But I get why developers prefer not to add a line above each individual method inside every React component.

  2. Class Autobind - The package we chose in BigPanda. It uses a function inside your constructor that automatically binds the Component’s methods to the instance itself:

    class MyComponent extends React.Component {
    constructor(props) {

    In case you plan to subclass the component, specify the prototype as the second parameter.

  3. React Autobind - Useful when you want to select specific methods to bind.

Let me know if you have different solutions.

comments powered by Disqus