2

I found in an open source project a class like this

class ComponentName extends React.Component{
  state = {
    somestate here
  };

  render() {
    return <RenderedComponent value={somethings}>{some other things}</RenderedComponent>;
  }
}

is it correct to define state in this way? Shouldn't it be defined inside the class's constructor?

marco
  • 1,152
  • 1
  • 9
  • 20

4 Answers4

3

You don't always have to define a constructor for every class. So if you don't need to define a constructor it is fine to use the state this way.

Hbarna
  • 425
  • 3
  • 16
2

Yes, it is perfectly correct, check this link: https://github.com/the-road-to-learn-react/react-alternative-class-component-syntax

You can do it both ways, in the constructor or using class field declarations.

Oriol Grau
  • 609
  • 6
  • 8
1

yeah you can define like this it's experimental state that works similar to constructor state.

  • The only thing is you need to define arrow function instead of binding(if using experimental state).

  • If you define constructor then you can bind function there

experimental state

state = {
name: 'hello'

}

state defined in constructor where you can bind function

constructor(props) {
super(props);
this.state = {
  name: ': hey'
}
this.handleChange = this.handleChange.bind(this);

}

akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
1

It is a new syntax of ES6. It is 100% equal define state without constructor and define state inside constructor. So feel free to write this way. To learn more about it check their documentation.