Answered
For my React.js component, I need to create a this.state
object I can reference.
How can I do that?
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>
)
}
}