I am confused that should I bind fat arrow function or not in ReactJS?
normal functions does not work properly without binding but I dont know about fat arrow functions should be binded or not
I am confused that should I bind fat arrow function or not in ReactJS?
normal functions does not work properly without binding but I dont know about fat arrow functions should be binded or not
No, you do not need to bind this
for arrow functions. They have the same this
value as the enclosing context.
this.myValue = 5;
const myFunc = () => {
this.myValue = 10;
}
myFunc();
console.log(this.myValue); // 10
See here for more details.
If your binding function needs this
(wich seems mandatory), you effectively need to bind correctly the this
. The best way (recommanded by the airbnb eslinter) is the fat arrow function.
As an exemple, let's assume I have this component :
class MyComponent extends React.Component {
toBeRunOnSpanClick() {
this.props.clickHandler();
}
render() {return <span onclick={/* What should you use here*/}></span>}
}
This won't work :
class MyComponent extends React.Component {
toBeRunOnSpanClick() {
this.props.clickHandler();
}
render() {return <span onclick={this.toBeRunOnSpanClick}></span>}
}
The this
in your toBeRunOnSpanClick function won't be the same than your class. That is the way javascript works.
The good way will be :
class MyComponent extends React.Component {
toBeRunOnSpanClick() {
this.props.clickHandler();
}
// this.toBeRunOnSpanClick.bind(this) will work too but it is way less comprehensive
render() {return <span onclick={() => {this.toBeRunOnSpanClick()}}></span>}
}