9

I am currently working on a react app, and I found having to bind this a bit cumbersome when a component class has many functions.

Example

class Foo extends Component {
  constructor(props){
    super(props);
    this.function1 = this.function1.bind(this);
    this.function2 = this.function2.bind(this);
    this.function3 = this.function3.bind(this);
  }
  function1() {
    ...
  }
  function2() {
    ...
  }
  function3() {
    ...
  }
}

Is there a more efficient way to do this?

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Faraz Khan
  • 103
  • 3

2 Answers2

10

You can avoid having to bind methods by using the transform-class-properties Babel plugin, which is an experimental ES7 feature. Make sure you enable stage-0 in order to use it.

This allows the use of arrow functions when defining your class methods, leveraging arrow functions' lexical binding so this refers to function's context (in this case the class), like so:

class Foo extends Component {
    boundFunction = () => { /* 'this' points to Foo */ }
}
mic-css
  • 118
  • 1
  • 5
  • Unless I'm sorely mistaken, this is fixing a different problem. See my answer below. – J__ Jan 12 '17 at 17:36
  • @J__ see my comment on your answer. In the case of React components, op is correct. I have submitted an edit to make the question specific to this. – mic-css Jan 13 '17 at 09:48
1

You can shorten it a bit with:

this.function1 = ::this.function1

You'll need https://babeljs.io/docs/plugins/transform-function-bind/

Miloš Rašić
  • 2,229
  • 5
  • 24
  • 43