The right way to bind custom methods in ES6 Class React Component
When using ES6 version of defining a React Component,
DONT
class A extends React.Component {
myFunction() {
// you'd want to use `this` here
}
componentDidMount /* or some react component lifecycle method */() {
// Never do .bind(this) at the place of subscription
SomeEvent.subscribe(this.myFunction.bind(this));
}
componentWillUnmount() {
// because, now this will not work
SomeEvent.unsubscribe(this.myFunction.bind(this));
}
}
DO
class B extends React.Component {
constructor(...args) {
super(...args);
// bind it and make it an instance method instead of prototype method
this.myFunction = this.myFunction.bind(this);
}
myFunction() { /* this */ }
componentDidMount() {
SomeEvent.subscribe(this.myFunction);
}
componentWillUnmount() {
SomeEvent.unsubscribe(this.myFunction);
}
}
BUT
const C = React.createClass({
//- - - - - - ^ - the magic happens here
myFunction() {
// this
},
componentDidMount() {
SomeEvent.subscribe(this.myFunction);
},
componentWillUnmount() {
SomeEvent.unsubscribe(this.myFunction);
}
});
Inspired from this article - [https://www.webreflection.co.uk/blog/2015/10/22/how-to-add-dom-events-listeners] by
@WebReflection
This is also, mentioned in the official React docs - [https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding].
Written by Boopathi Rajaa
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#React
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#