Log 09 · From the 2016 archive
ReactJS Bind Hell
- Filed
- Reading
- 1 min
I (along with many others) hate having to call React’s components methods with something that looks like: this.method.bind(this). If you don’t know what I’m talking about, read more about it in this post(opens in new tab).
In my projects, I add to the React.Component class prototype, a helper method which helps me remove those crazy bindings. I do, at top level file, the following addition to the Component class:
// Deps =========================================
import React from 'react';
...
// Adding _bind helper to Components ============
React.Component.prototype._bind = function _bind(...methods) {
methods.forEach((method) => {
this[method] = this[method].bind(this);
});
};
Pretty neat, right? Each argument, will be the name of the method to bind the context to. Here a little counter to show you how to use it:
// Item class ===================================
class Item extends Component {
constructor() {
super();
//== Initial State
this.state = {
count: 0
};
//== Save initial state
this.baseState = this.state;
//== Pre-bind all events handlers
this._bind('handleClick', 'handleReset');
}
handleClick(evt) {
let { count } = this.state;
count += 1;
this.setState({ count });
}
handleReset(evt) {
this.setState({ this.baseState });
}
render() {
const { handleClick, handleReset, state } = this;
const { count } = state;
return (
<div>
{ `Clicks Count: ${count}` }
<button onClick={ handleClick }>Increment</button>
<button onClick={ handleReset }>Reset</button>
</div>
);
}
}
Look at the constructor there is a this._bind() method. We pass the methods to add context to, like string arguments, and the _bind method in the prototype, binds the component this context to them. This way, we can simply call the component’s method without binding on each call.