0

I've always done the following to bind this of a function in a React component

this.updateInput = this.updateInput.bind(this);

but I've been seeing more and more of the arrow method outside the constructor like so

updateInput = () => ( code here )

but when I try this in my code it throws a syntax error. Why?

Jstuff
  • 1,266
  • 2
  • 16
  • 27

2 Answers2

2

I believe you're referring to syntax like this:

class MyClass {
    constructor() {

    }
    myBoundFunction = () => { //<--- this line inside of a class

    }
}

Declaring arrow functions as part of the class definition is an experimental feature that's not a standard part of the javascript language, which is why you're seeing a syntax error. If you want to use this syntax, you can use Babel's transform-class-properties feature

If you're not using babel, then you'll need to manually bind the function inside your constructor.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • In your opinion what is the best way to approach this problem in React? I had an interview and was asked why did I use `.bind(this)` and not an arrow function. – Jstuff Sep 23 '17 at 17:25
  • The difference between doing `.bind(this)` in the constructor vs creating an arrow function in the constructor, vs using babel to use the special syntax above is negligable in my opinion. They're all doing essentially the same thing just with different syntax, so the choice mostly comes down to which you and your team find easiest to understand. For what it's worth, most of the examples on the react website use `.bind(this)` – Nicholas Tower Sep 23 '17 at 18:01
  • One thing you do want to make sure of is that whatever approach you're using, you do it in the constructor (or the babel way, which transpiles to doing it in the constructor). That way, it's just done once for each instance of the class. If you're doing the binding multiple times (say, on every render call), then you may have a performance impact. – Nicholas Tower Sep 23 '17 at 18:03
0
  1. You want to use .bind(this) in class constructor only.
  2. You either want to use this.updateInput or () => updateInput()
  3. If you want to use this.updateInput you have to define it like updateInput = () => ( code here ) in your class then use it as onSomething={updateInput] in your class.
  4. If it throws syntax error. When you bind this in constructor your event handler is ready to do some stuff. All you have to do then is eventHandler={this.updateInput}
Michal
  • 4,952
  • 8
  • 30
  • 63