
ReactJS
Error Boundaries catch errors in child components and display a fallback UI instead of crashing.
ā Caught by Error Boundaries:
ā NOT Caught:
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.log("Error caught:", error);
console.log("Error info:", errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div>
<h1>Something went wrong</h1>
<p>{this.state.error?.message}</p>
</div>
);
}
return this.props.children;
}
}function App() {
return (
<ErrorBoundary>
<Header />
<MainContent />
<Footer />
</ErrorBoundary>
);
}
function MainContent() {
// If this throws, ErrorBoundary catches it
throw new Error("Component failed!");
}function App() {
return (
<div>
<ErrorBoundary>
<Header />
</ErrorBoundary>
<ErrorBoundary>
<UserProfile />
</ErrorBoundary>
<ErrorBoundary>
<ChatWindow />
</ErrorBoundary>
</div>
);
}function FallbackUI({ error }) {
return (
<div style={{ padding: "20px", backgroundColor: "#ffebee" }}>
<h2>Component Error</h2>
<p>{error.message}</p>
<button onClick={() => window.location.reload()}>
Reload Page
</button>
</div>
);
}
class ErrorBoundary extends React.Component {
// ... error handling code ...
render() {
if (this.state.hasError) {
return <FallbackUI error={this.state.error} />;
}
return this.props.children;
}
}Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep ⢠Build Real ⢠Verify Skills ⢠Launch Forward