0

I am attempting to run a few arrow functions within my react code, but despite adding babel loaders to build the code in a readable format, I am receiving an error at the = portion of my arrow functions.

export default class CommentForm extends React.Component {
    constructor(props){
        super(props);
        ...
        this.state = {
            value: '',
            flash: '',
            suggestions: [],
        };

        this.onChange = this.onChange.bind(this);
        this.focus = this.focus.bind(this);
    }
    ...
    onChange = (editorState) => {
        this.setState({
            suggestions: ['test']
        });
    }
    ...
}

Error:

ERROR in ./public/components/app/activity-feed/feed/VerticalTimeline/CommentComponents/CommentForm.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (150:13)

webpack.config.js:

module.exports = {
    mode: 'development',
    entry: "./public/index.js",
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
    },
    module: {
        rules: [
            {   
                test: /\.js$/, 
                exclude: /node_modules/, 
                loader: "babel-loader"
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            }
        ]
    },
};

package.json:

  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    ....
  }
4
  • FYI If you use arrow function syntax, you can't bind them to an object. Remove the this.onChange = this.onChange.bind(this); in your constructor. Commented Jan 31, 2019 at 1:41
  • Thanks for the answer. I removed the bind, but still receiving the same error. Any other suggestions? Commented Jan 31, 2019 at 1:43
  • what's your babel configuration look like? .babelrc, package.json, wherever you're keeping it Commented Jan 31, 2019 at 1:45
  • { presets: [ "es2015", "react" ] }, which is located in .babelrc Commented Jan 31, 2019 at 1:49

1 Answer 1

2

You are trying to define class properties using the equal sign. This is still a proposal so it will not work out of the box using babel. What you need is a plugin.

npm install --save-dev @babel/plugin-proposal-class-properties

//.babelrc
{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

A cool feature of this proposal is that it creates bounded functions. So there is no need to use .bind in constructor anymore! You can read more about it here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.