Learn

At this point, our ErrorBoundary component isn’t truly an error boundary. It still is letting errors through that cause the entire application to break. To make our error boundary actually protect our application, we need to:

  • Identify when an error has occurred
  • Store the error internally
  • Render a fallback UI

First, we can keep track of whether or not an error is present using the ErrorBoundary component’s internal state. In the constructor(), we’ll add some state:

constructor(props) { super(props); // New code this.state = { error: null }; }

Notice that our state starts with error having a null value, i.e. there is no error. Next, to update this value when an error occurs we define the special static lifecycle method static getDerivedStateFromError():

constructor(props) { //… } // New code static getDerivedStateFromError(error) { return { error }; } render() { //… }

This lifecycle method is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return the error boundary’s next state. In this case, we want to return the error that the component received.

Note: We use ES6 shorthand here. { error } is equivalent to { error: error }.

Finally, we can use the error boundary’s this.state.error value to determine what to render: the wrapped component tree or the fallback UI.

render() { // New code if (this.state.error) { // Render a fallback if an error occurred return ( <div> <h2>An error was detected!</h2> </div> ); } return this.props.children; // Otherwise, render the children! }

Now, our error boundary first checks its own internal this.state.error value before rendering its children. If an error is found, the fallback UI is displayed instead.

Let’s try it out!

Instructions

1.

Let’s update our ErrorBoundary component to render a fallback UI when an error occurs. First add a state value to track the existence of an error.

2.

Next, define the static getDerivedStateFromError() lifecycle method. It should return the new state for the error boundary once an error is found.

3.

Finally, add a conditional statement to the render() method to render a fallback UI if the error state value is true. This fallback UI should be a <div> element with an <h2> element nested inside. The <h2> element can include any message you choose!

4.

Now, test your application.

  1. First, press either of the error buttons for switch 1 or 2. Notice that the on/off switches for switch 3 and 4 still work. Refresh the mini-browser after you have checked switches 3 and 4.
  2. Next, click the error button for switch 3. Notice how the on/off switches for switches 1, 2, and 4 still work. Refresh.
  3. Finally, click on the error button for switch 4. Notice how the entire application crashes.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?