3

If you need to specify initial state in a class, I see people did this

class App extends React.Component {
   constructor() { super(); this.state = { user: [] } }
   render() {
      return <p>Hi</p>
   }
}

but what's wrong without a constructor?

class App extends React.Component {
   state = { user: [] }
   render() {
      return <p>Hi</p>
   }
}

1 Answer 1

11

but what's wrong without a constructor?

There is nothing "wrong" with it. But it uses the class properties proposal which is not officially part of the language yet (since you tagged the question with : It is not part of ES6). So you have to correctly configure your build system to be able to use it (in addition to what's needed for JSX).

Sign up to request clarification or add additional context in comments.

3 Comments

Just an addition to Felix's answer: If you don't want to use the constructor (I'm not a fan of it) you can also use componentWillMount to set the state with setState(...). Then you don't need the super() call which saves a few lines of code.
@Tobias isn't it just simply do state = {myapp:'something'} will do? why need to setState with componentWillMount at all?
Well most of the time I‘m not just setting static values, but computed ones. That‘s not possible with class properties. To unify my code I use componentWillMount everywhere

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.