Code
CSS
HTML
Editor
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error(
"Caught by boundary:", error, errorInfo
);
}
render() {
if (this.state.hasError) {
return (
<div>
<h1>Oh bugger!</h1>
<pre>
{this.state.error.message}
</pre>
</div>
)
}
return this.props.children;
}
}
import { render } from 'react';
function BuggyComponent() {
throw new Error("Something went wrong!");
return <div>Never</div>;
}
function App() {
return (
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
)
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
Let's create and use our Error Boundary.
We mentioned earlier that the error boundary must be a class component, as it uses some React wiring not available in functional components.
In the constructor, we initialise the state, in our case, he will track whether the component caught an error and what is its value.
The getDeriverdStateFromError is a special static function that parses an incoming error and returns what interests us. In our case, it prepares state variables, saying that hasError must be set to true, and passs down the error itself.
The componentDidCatch method is another special method executed when an error is caught during React rendering. It has two parameters, an error itself and erroInfo, which is returned by the getDerivedStateFromError function we just set up. In this method, we should probably also notify the website admin that the website encountered an error or at least store it in the application lof for further investigation!
In the render method, we have to return the HTML code, in this case we just return children if there is no error, otherwise, we show an error message,
When we execute this code, we see that the Error Boundary caught this error and correctly rendered the error message received from the component. Mission Accomplished!