Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to bind 'this' in React Component classes?

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?

like image 790
5 revs Avatar asked Jan 12 '17 16:01

5 revs


People also ask

What is the alternative of binding this in the constructor?

First Method: We can use an arrow function in the render method where we are attaching the event handler. There is one performance implication in this method i.e. whenever the component re-renders the function will be created again and again.

How do you bind this in React?

ReactJS bind() Method The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component. Syntax: this. function.

Why we need to bind this in React?

You use bind to maintain the scope to the this . In the context of react this allows you to call things like this. setState etc.


2 Answers

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 */ }
}
like image 141
mic-css Avatar answered Oct 22 '22 04:10

mic-css


You can shorten it a bit with:

this.function1 = ::this.function1

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

like image 45
Miloš Rašić Avatar answered Oct 22 '22 03:10

Miloš Rašić