Share
How to Define State?
Question
- State of a component should prevail throughout the lifetime, thus we must first have some initial state, to do so we should define the State in the constructor of the component’s class.
- To define a state of any Class we can use the sample format below
Class MyClass extends React.Component {
constructor(props) {
super(props); this.state = { attribute : “value” };
}
}
- Writeable/Mutable Let’s create an user component with message state,
- Has setState() method to modify properties.
class User extends React.Component {
constructor(props) {
super(props) this.state = { message: ‘Welcome to React world’ }
}
render() {
return ( <div> <h1>{this.state.message}</h1> </div> )
}
}
Leave an answer