Learn

We are now able to replace our custom ErrorBoundary with the ErrorBoundary component from react-error-boundary — but there are some features that we lost. Specifically, we don’t have error logging and the reset component feature!

Thankfully, react-error-boundary has built-in implementations for adding in these important features. Let’s take a look.

First, we can see how to add error logging with the onError prop:

<ErrorBoundary onError={logError} FallbackComponent={ErrorFallback}> <MyComponent/> </ErrorBoundary>

In this example, we add the onError prop with our logging function logError as the value. onError will send along two familiar values to the provided function: error and errorInfo. Notice that these are the same arguments passed to the componentDidCatch() lifecycle method.

Next, we can look at resetting the ErrorBoundary with the resetErrorBoundary prop:

function ErrorFallback({ error, resetErrorBoundary }) { return ( <div> <h2>An error occurred in the app!!</h2> <p>Error: {error.message}</p> <button onClick={resetErrorBoundary}> Reset </button> </div> ); }

When our ErrorBoundary renders a fallback component, it will pass in two values as props: error and resetErrorBoundary.

  • error is the Error object itself which can be useful if we want to display the error.message.
  • resetErrorBoundary is a callback function that will reset the internal error state of the ErrorBoundary itself. This callback can be assigned to the onClick prop of the button element in our fallback UI.

With this code in place, when the user clicks on the “Reset” button in our fallback UI, the ErrorBoundary will reset and attempt to re-render the broken child component.

Note: If you take a look at the source code for this feature, you can see that it’s basically the same as our own implementation!

Instructions

1.

Let’s add logging and resetting back into our application. First add an onError prop to each of the ErrorBoundary components. The value of this prop should be the imported logError function. Remember to pass in logError as a function, without having invoked it.

Test out your “Bad Switch” buttons, they should now produce the familiar red error-logging message.

2.

Next, let’s modify the ErrorFallback component. In the parameter list, destructure the error and resetErrorBoundary props.

3.

Below the <h2> element and inside the <div> returned by your ErrorFallback component, add in a <button> element with the text Reset. It should have an onClick property with a value of resetErrorBoundary. Again, no need to call this function when assigning to the onClick property.

4.

Finally, add a <p> element that renders the .message property of the error prop like so:

<p>Error: {error.message}</p>

With everything in place, test your code!

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?