1

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.

1 Answer 1

1

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
  };
}  
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.