Error Boundary Component
ReactJS
Hard
5 views
Problem Description
Create an ErrorBoundary that catches render errors and shows a fallback UI.
Output Format
Render a React component.
Constraints
Use a class component and componentDidCatch.
Official Solution
import React from 'react';
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <div style={{ padding: 16, border: '1px solid #ffc2c7', background: '#ffe8ea', borderRadius: 14 }}>Something went wrong on meetcode.</div>;
}
return this.props.children;
}
}
function Buggy({ crash }) {
if (crash) {
throw new Error('Crash');
}
return <div>All good</div>;
}
export default function App() {
return (
<ErrorBoundary>
<Buggy crash={true} />
</ErrorBoundary>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!