How to handle errors in a component and state in React.js?

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.

Leave a Comment