1 | initial version |
React Error Boundary is a higher-order component that catches JavaScript errors anywhere in their child component tree and logs them. Here's how you can use it to catch errors occurring in an inner component:
import React, { Component } from 'react';
class ErrorBoundary extends Component {
state = {
hasError: false,
error: null,
info: null
};
componentDidCatch(error, info) {
this.setState({ hasError: true, error, info });
}
render() {
const { hasError, error, info } = this.state;
if (hasError) {
return (
<div>
<h2>Something went wrong.</h2>
<p>{error.toString()}</p>
<p>{info.componentStack}</p>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
function MyComponent() {
// code for MyComponent
}
function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}
export default App;
Now, any error thrown by the MyComponent
will be caught by the ErrorBoundary
and displayed as an error message.