đ¨ Error Boundries
How do Error Boundaries work in React?
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log('something went horribly wrong', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Fallback UI</h1>;
}
return this.props.children;
}
}
// Example Usage
function Main() {
return (
<Dashboard>
<ErrorBoundary>
<Orders />
</ErrorBoundary>
</Dashboard>
);
}
Challenge
Create an ErrorBoundary
class component that provides a fallback UI in the event an error occurs.