-1

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

Naveed Aheer
  • 1,715
  • 6
  • 25
  • 40
  • 2
    Possible duplicate of [How to use ES6 arrow in class methods?](http://stackoverflow.com/questions/31362292/how-to-use-es6-arrow-in-class-methods) – Suraj Rao Apr 20 '17 at 12:01
  • `myFunc.bind(this)` works the same as `() => this.myFunc()`. – Sulthan Apr 20 '17 at 12:19

2 Answers2

1

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.

Michael Peyper
  • 6,814
  • 2
  • 27
  • 44
1

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>}
}
Julien TASSIN
  • 5,004
  • 1
  • 25
  • 40