Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React only binds Component methods to this - work around?

Tags:

reactjs

Is there a way to avoid the boilerplate when using ES6 with react 0.14?

Until now I didn't have to worry about my function to be bound to the Component I created but that is no longer (why?!?) the case and the Component is only bounded to the Component super class (If I understood the errors correctly).

So what I really need to do each time I create a new class is to add this code to the constructor:

class CustomComp extends React.Component {

  constructor() {
    super();
    this.newFunction = this.newFunction.bind(this);
  }

  newFunction(){
    console.log('This is user defined function');

}
  render() {
    return <button onClick={this.newFunction}>Click</button>
  }
}

So if I wont bind newFunction it will fail (no props, state or anything).

Is there a way to work around this?

like image 606
Shikloshi Avatar asked Nov 07 '15 12:11

Shikloshi


Video Answer


1 Answers

From the React documentation:

No Autobinding

Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.

So, no there is not an automatic way to bind all methods that is new in 0.14. But, as the documentation suggests, you can:

1) use arrow functions (However, if you are using Babel, you need stage 0):

class CustomComp extends React.Component {

  constructor() {
    super();
  }

  newFunction = () => {
    console.log('This is user defined function');

}
  render() {
    return <button onClick={this.newFunction}>Click</button>
  }
}

2) you can bind in place:

class CustomComp extends React.Component {

  constructor() {
    super();
  }

  newFunction() {
    console.log('This is user defined function');

}
  render() {
    return <button onClick={this.newFunction.bind(this)}>Click</button>
  }
}

3) you can use an arrow function in place (which is like a bind):

class CustomComp extends React.Component {

  constructor() {
    super();
  }

  newFunction() {
    console.log('This is user defined function');

}
  render() {
    return <button onClick={() => this.newFunction()}>Click</button>
  }
}

I tend to use number 2 & 3 if I only have a 1-2 methods. Number 1 is good, but you have to remember the syntax for every method definition. If I have a lot of methods, I do tend to bind in the constructor.

like image 72
Davin Tryon Avatar answered Oct 19 '22 23:10

Davin Tryon