How to use states in React.js »
Let’s try to simulate some errors in your App component to learn how to deal with them.
Add a new property called hasError to the state in App component and initialize it with default value of true as follows:
this.state = {hrs: '', hasError: true};
Next, make these changes to the render() method:
render(){ if (this.state.hasError){ return <div>An error has occurred!</div>; } return <div>Current hour is: {this.state.hrs}</div>; }
This time, the value hasError is true, therefore, you should see:
An error has occurred!
Change the default value to false, like this:
this.state = {hrs: '', hasError: true};
And you should see:
Current hour is: 1
It simply means that you can do conditional rendering in a component based on the state object properties.
Table of Content
- What are the requirements of using states in React.js?
- How to initialize states using constructors in React.js?
- Why do we need to call super(props) in constructor function in React.js?
- How to initialize default state object in constructor in a component in React.js?
- How to update state properties in a component in React.js using setState()?
- How the app lifecycle works in React.js?
- How to handle errors in a component and state in React.js?