Error Boundary with Fallback UI
Showcase an Error Boundary that catches errors and renders a fallback UI to gracefully inform the user.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so next render shows fallback UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// Render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
This is an Error Boundary component that catches JavaScript errors in its child component tree, logs the error, and displays a fallback UI instead of the component tree that crashed. 'getDerivedStateFromError' is used to render the fallback UI when an error is caught.
const MyComponent = () => {
// This component is meant to be wrapped in ErrorBoundary
// It intentionally throws an error for demonstration
throw new Error('I crashed!');
return <div>This will not render</div>;
}
This is a component that simulates a JavaScript error by throwing an error when it's rendered.
const logErrorToMyService = (error, errorInfo) => {
// Send the error to an error reporting service
console.error('Logging to my service:', error, errorInfo);
}
This function simulates logging the error to an external error reporting service. Replace the `console.error` call with integration to a real service.
ReactDOM.render(
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>,
document.getElementById('root')
);
This is the root of the application where 'ErrorBoundary' wraps 'MyComponent'. If 'MyComponent' crashes, 'ErrorBoundary' will display a fallback UI to the user.