21

I've started a project where I use React JS for the front end an node js in backend. I used webpack for bundling up JS files. I used babel along with other necessary stuff. When I use arrow functions inside a react class, it gives a syntax error, like:

Module build failed: SyntaxError: Unexpected token

But I can use Arrow function in node without any issue.

This is my webpack config file:

import path from 'path';
import webpack from 'webpack';
import 'react-hot-loader/patch';

export default{
  devtool: 'eval',
  entry:[
    'react-hot-loader/patch',
    'webpack-hot-middleware/client?reload=true',
    path.join(__dirname,'client/index.js')],
  output:{
    path:'/',
    publicPath:'/'
  },
  plugins:[
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()

  ],
  module:{
    loaders:[
      {
        test:/\.js$/,
        include:path.join(__dirname,'client'),
        loaders: ['react-hot-loader/webpack', 'babel']
      },
      {
        test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i,
        loader: 'file-loader?name=[name].[ext]'
      }
    ]
  },
  resolve:{
    extension:['','.js']
  }
}

My React file:

class mapSidebar extends React.Component{

    constructor(props,context){
       super(props,context);
       this.state = {
         dataSource: []
       };
         this.handleUpdateInput = this.handleUpdateInput.bind (this);
    }

    handleUpdateInput = (value) => {
      this.setState({
        dataSource: [
          value,
          value + value,
          value + value + value,
        ],
      });
    };

    render(){
      return(
        <div>
          <Paper zDepth={2}>
            <div>Hello</div>
            <div>
                <AutoComplete
                  hintText="Type anything"
                  dataSource={this.state.dataSource}
                  onUpdateInput={this.handleUpdateInput}
                />
          </Paper>
        </div>
      );
    }

}

export default mapSidebar;

How to resolve this issue?

TRomesh
  • 4,323
  • 8
  • 44
  • 74

2 Answers2

48

It's not the arrow function that's causing a problem here. Class properties are not part of the ES6 specification.

handleUpdateInput = (value) => {
  // ...
};

If you want to be able to transform this code, you'll need to add the class properties babel plugin.

Alternatively, this transform is provided as part of Babel's stage 2 preset.

Using an arrow function with a class property ensures that the method is always invoked with the component as the value for this, meaning that the manual rebinding here is redundant.

this.handleUpdateInput = this.handleUpdateInput.bind (this);
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
3

It is not a problem of arrow function but using it inside class declaration, this code will work in constructor body or any other function body but not in class declaration.

Code should look just like that:

handleUpdateInput(value){
  this.setState({
    dataSource: [
      value,
      value + value,
      value + value + value,
    ],
  });
};

Using arrow function can be done inside any class method, but not inside class declaration. For example using arrow function in constructor:

constructor(props,context){
   super(props,context);

   this.someFunc = ()=>{
     //here function code
   };
}
Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50
  • 1
    Yes you are right i used it out side of the react class and it worked. but i have seen some examples where people have used it inside react class – TRomesh Dec 30 '16 at 15:42
  • 1
    @TRomesh but I see no advanceses in using arrow function here in class, really. Maybe this plugin can help - https://babeljs.io/docs/plugins/transform-class-properties/. But what is point doing that? – Maciej Sikora Dec 30 '16 at 15:46
  • 3
    @MaciejSikora It autobinds the component as `this` inside the method, which prevents you from needing to rebind or define functions in your constructor (losing the ability to share methods with prototypes). – Dan Prince Dec 30 '16 at 15:48
  • @DanPrince yes I get Your point. – Maciej Sikora Dec 30 '16 at 15:51