React program works fine on jscomplete.com/repl but the same code gives me the following error when I run in my browser

React program works fine on jscomplete.com/repl but the same code gives me the following error when I run in my browser, writing my code in my editor and using babel.

babel-browser.min.js:41 Uncaught SyntaxError: http://localhost/react1/app.jsx: Unexpected token (2:14)
  1 | class Button extends React.Component{
> 2 |   handleClick = () => {
    |               ^
  3 |     this.props.onClickFunction(this.props.incrementValue);
  4 |   }
  5 |   render() {

Upvotes: 1

Views: 765

Answers (1)

Samer Buna
Samer Buna

Reputation: 9311

The handleClick function in that code is defined as a class instance field which is not yet part of JS (currently at stage 2)

To make it work, you have to configure Babel with one plugin that includes it (for example, babel-preset-stage-2, or directly babel-plugin-transform-class-properties).

Alternatively, use a normal function definition in the class and bind it to this inside the constructor of the component.

Upvotes: 2

Related Questions