Ben Ben - 5 months ago 34
React JSX Question

can i 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...
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
to, for instance
, it would be scoped to the class instance, and not the

Guy Guy

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 for ES7. 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 ES7 proposal for Class Fields and Static Properties here