This example shows an error boundary catching an error from a child component. Instead of crashing, it shows a friendly message.
import React, { Component } from 'react';
import { createRoot } from 'react-dom/client';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log('Error caught:', error.message);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function BuggyComponent() {
throw new Error('Bug!');
return <div>This will not render</div>;
}
function App() {
return (
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
);
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);