0

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?

0

2 Answers 2

1

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

Comments

0

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.

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.