A babel plugin to auto bind you class methods
npm install babel-plugin-auto-binderthis. Example:this.doStuff = this.doStuff.bind(this);
Now if you forget to bind your method, you will face very weird bugs which can be frustating. babel-plugin-auto-binder will take care of this issue by doing this binding behind the scene so you just worry about the functionality.
If you are using or prefer using arrow functions then you don't need this plugin as the arrow function have the this context from the scope they are declared in.
npm i -D babel-plugin-auto-bindernpm i -D babel-plugin-transform-decorators-legacy.babelrc configuration by adding
{
"plugins" : [
"auto-binder",
"transform-decorators-legacy",
]
}
`
$3
Decorate your class with @autobind decorator like this:
`
@autobind
class App extends Component {
constructor() {
super();
} doStuff() {
//some api calls
}
render() {
return (
)
}
}
`
and that's it!!The above input will get transformed to
`
class App extends Component {
constructor() {
super(); this.doStuff = this.doStuff.bind(this);
}
doStuff() {
//some api calls
}
render() {
return (
)
}
}``