Ben Ben - 21 days ago 4
React JSX Question

How to use ES6 arrow in class methods?

I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with CoffeeScript:

class SomeClass extends React.Component {

// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}

// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}


So that if I were to pass
SomeClass.handleInputChange
to, for instance
setTimeout
, it would be scoped to the class instance, and not the
window
object.

Guy Guy
Answer

Your syntax is slightly off, just missing an equals sign after the property name.

class SomeClass extends React.Component {
  handleInputChange = (val) => {
    console.log('selectionMade: ', val);
  }
}

This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.

To use experimental features in babel you can install the relevant plugin from here. For this answers feature, this plugin is needed.

You can read more about the proposal for Class Fields and Static Properties here


Comments