Implementing an Error Boundary
Learn how you can catch possible errors in your application and prevent users from experiencing a mishap.
We'll cover the following...
There are two simple rules when it comes to implementing an error boundary:
- Only Class components can be turned into an error boundary.
- The class has to implement the static
getDerivedStateFromError()
method or the class methodcomponentDidCatch()
(or both of them).
Strictly speaking, we are already dealing with an error boundary from a technical point of view if one or both of the methods mentioned above have been implemented. All other rules that apply to regular class components also apply to error boundary.
Let’s look at an implementation of an error boundary:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app.js'; require('./style.css'); ReactDOM.render( <App />, document.getElementById('root') );
The console would look like this once you press the button:
Defining a new component
First, we define a new component. We have named this component ErrorBoundary
, but it is possible to give it any other ...