← coderrocketfuel.com

Create a this.state Object for a React.js Component

How do you create a this.state local state object for a React.js component?

You do this in the constructor(), which is a class constructor that's called before your React.js component is mounted.

It'd look like the following:

constructor(props) {
  super(props)
  this.state = {
    loading: false,
    title: "Example title"
  }
}

This will make this.state accessible to your component on a locally specific level. And you can make updates to it using the this.setState() method.

super(props) is called to ensure this.props is not undefined inside the constructor(), which could cause issues.

The constructor() should be positioned at the top of the component:

class YourComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      title: "Example title"
    }
  }

  render() {
    return (
      <div>{ this.state.title }</div>
    )
  }
}

As an example, the title state value is accessible via { this.state.title }. And the values in this.state will be local to only this component.

Thanks for reading and happy coding!