Wei Zhang
Wei Zhang

Reputation: 110

Module build failed: SyntaxError: Unexpected token

I am new to React. I try to run the example code from the online learning resource but I got the error that makes me completely confused. Could anyone tells me what exactly went wrong?

I create a Refs.js and the code is listed below

import React, { Component } from 'react';

class Refs extends Component {

  state = { liked: false }

  handleClick = (event) => {
    this.setState({liked: !this.state.liked});
  }

  render() {
    let text = this.state.liked ? 'Like' : 'Dislike';

    return (
      <p onClick={this.handleClick}>
        I {text} Apple.
      </p>
    );
  }
}

export default Refs;

And I got error Module build failed: SyntaxError: Unexpected token

   5 | class Refs extends Component {
   6 | 
>  7 |   state = { liked: false }
     |         ^
   8 | 
   9 |   handleClick = (event) => {
  10 |     this.setState({liked: !this.state.liked});

Also, I found the coding style on different online resource for React has huge difference to each other(Such as class Refs extends Component or class Refs extends React.Component or var Refs = React.createClass). Could anyone tell me what is the exact code standard for react? I found learning React is really confusing by comparing to JQuery/Angular I have learnt before. Now I don't even sure whether or not I can declare a variable in the class. I know I put a lot of the question in this single thread. But I do really hope someone can help me to resolve my confusion. Thank you in advance.

Upvotes: 1

Views: 714

Answers (1)

Jasmine
Jasmine

Reputation: 48

You need to add a constructor function as specified in the docs here

In you case it will be something like this

constructor(props) {
  super(props);

  this.state = {
      liked: false
  };
}  

Upvotes: 1

Related Questions