Typically error boundary components are created once and then used throughout the entire application where needed. Once the error boundary component has been set up, there isn’t much need to modify its code. As a result, it’s not common for programmers to create their own ErrorBoundary
components in the first place. Instead, they will often turn to implementations such as the popular react-error-boundary
package.
This package exports an ErrorBoundary
component that does all of what our ErrorBoundary
component can do plus more! To replicate the basic fallback UI behavior of our own custom ErrorBoundary component, we could write:
import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback() { return ( <div> <h2>An error was detected!!</h2> </div> ); } function App() { return ( <ErrorBoundary FallbackComponent={ErrorFallback}> <MyComponent /> </ErrorBoundary> ); }
In this example, we:
- Import the
ErrorBoundary
component from'react-error-boundary'
. - Define an
ErrorFallback()
component with UI to render if the ErrorBoundary catches an error. - Render the
ErrorBoundary
with our component nested inside. - Pass a
FallbackComponent={ErrorFallback}
prop toErrorBoundary
. When theErrorBoundary
catches an error, theErrorFallback
component renders instead!
At this point, this ErrorBoundary
doesn’t have any logging or resetting behavior, but we’ll get to that in the next exercise. For now, let’s add the basic ErrorBoundary
to the lightswitch application!
Instructions
We’ve reset the application to its original state when we began the lesson. Currently none of the <LightSwitch>
components are protected with an error boundary. Let’s fix that, this time using react-error-boundary
!
First, import ErrorBoundary
from 'react-error-boundary'
(we’ve already installed the package for you).
Next, we will wrap our <LightSwitch>
components in separate error boundaries:
- Wrap the first two
<LightSwitch>
components in oneErrorBoundary
. - Wrap the third
<LightSwitch>
in anotherErrorBoundary
. - Leave the fourth
<LightSwitch>
unprotected.
For each ErrorBoundary
, pass a FallbackComponent
prop whose value is the ErrorFallback
component that has been provided for you.
Save your code and test out the application. You should have working error boundaries for the first three light switches!