.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.
To bind or not to bind? It’s all about those parens. pic.twitter.com/b7pi4kxyfi
— Dan Abramov (@dan_abramov) October 24, 2016
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)
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:
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.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) { super(props); autobind(this); }
In case you plan to subclass the component, specify the prototype as the second parameter.
React Autobind - Useful when you want to select specific methods to bind.
Let me know if you have different solutions.