Diego
Diego

Reputation: 111

ReactJS - Unexpected token '.' error

I am starting with my react project on VS2013 working together with ASP.NET MVC. I have configured webpack and configuration seemed working well until I tried to implement the following class.

class Hello extends React.Component {
    this.state = { visible: true }
    render() { 
       /** Method definition **/
    ...
}

I am getting an error Unexpected Token at '.' at 'this.state'. I have already check es2015 is set as babel preset. If I remove state and toggleVisibility assignments, webpack bundles OK.

Any idea what else can I try?

Upvotes: 0

Views: 773

Answers (2)

Mr. Alien
Mr. Alien

Reputation: 157284

You should define this.state in a constructor like

constructor(props) {
  super(props);
  this.state = { 
     visible: true 
  };
}

Hence, your code should be

class Hello extends React.Component {
  constructor(props) {
    super(props);

    this.state = { 
      visible: true 
    };
  }

  render() {}
}

From React docs:

The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.

Upvotes: 0

thangngoc89
thangngoc89

Reputation: 1400

It's a class so the correct syntax should be

class Hello extends React.Component {
    state = { visible: true }
    render() { 
       /** Method definition **/
    ...
}

Also, the recommended way of defining initial state should be

class Hello extends React.Component {
    constructor(props) {
      super(props)
      this.state = { visible: true }
    }

    render() { 
       /** Method definition **/
    ...
}

Upvotes: 1

Related Questions