How to create the this.state object for a React component?

Answered
nick asked this question 1 year, 6 months ago
nick on Dec 2, 2021 · Edited

For my React.js component, I need to create a this.state object I can reference.

How can I do that?

1 suggested answers
coderguy on Dec 8, 2021 · Edited

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

It'd look like this:

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

This will make this.state accessible to your component on a local 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 component:

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

  render() {
    return (
      <div>Page content</div>
    )
  }
}
0 replies
Answered