← React Beginner Questions - Set 4 Q31
React Beginner Questions - Set 4
A component that catches render-time errors in its subtree and shows a fallback instead of a blank page. They are still class-only.
import { Component } from 'react';
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
console.error('Boundary caught:', error, info.componentStack);
}
render() {
if (this.state.error) {
return <div role="alert">Something broke: {this.state.error.message}</div>;
}
return this.props.children;
}
}
// <ErrorBoundary><Chart /></ErrorBoundary>