Search code examples
reactjswebpackbabeljssemantic-ui-reactbabel-loader

SyntaxError on setting state in React


Here's the error I'm receiving:

ERROR in ./src/components/CustomHeader.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (17:10)

  15 | class CustomHeader extends Component {
  16 | 
> 17 |     state = {activeItem: 'home'};
     |           ^
  18 | 
  19 |     handleItemClick = (e, {name}) => this.setState({activeItem:name});
  20 | 

Her is my webpack.config.js file:

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    devtool: "cheap-eval-source-map",
    entry: path.join(__dirname, 'src', 'index.js'),
    output: {
        path: path.join(__dirname, 'dist'),
        filename: "bundle.js",
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: path.join(__dirname, 'src')
            },
            {
                test: /\.jsx$/,
                loader: 'babel-loader',
                include: path.join(__dirname, 'src')
            },
            {
                test: /\.css$/,
                loader: [ 'style-loader', 'css-loader' ],
                include: path.join(__dirname, 'src'),
            },
            {
                test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                loader: 'url-loader?limit=100000'
            },
            {
                test: /\.scss$/,
                use: [{
                    loader: 'style-loader',
                }, {
                    loader: 'css-loader',
                }, {
                    loader: 'sass-loader',
                }],
            }

        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        inline: true,
        hot: true,
        historyApiFallback: true,
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, 'src', 'index.html'),
            hash: true,
        })
    ]
}

.babelrc file:

{
  "presets": [
    "react",
    "env"
  ]
}

Do I need to change how I set state? Or is there something else that I need to import to my project? Any help would be appreciated. Thanks.

(Note: Code I'm using is taken straight from Semantic UI Examples at the moment.)


Solution

  • You need either stage-2 preset

    OR

    You can use babel-plugin-transform-class-properties.
    if you don't want to use stage-2 and stick with more stable stages.

    enter image description here

    Try out your combinations on BabelJS and pick your poison.