Skip to content

Instantly share code, notes, and snippets.

@mokargas
Created April 18, 2024 23:40
Show Gist options
  • Save mokargas/084c3604fa93962ec98664ce62aa0021 to your computer and use it in GitHub Desktop.
Save mokargas/084c3604fa93962ec98664ce62aa0021 to your computer and use it in GitHub Desktop.
Basic error boundary example
import React, { useState } from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { error: false }
}
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error, info) {
//For illustration purposes, we'll just log
console.debug('error detected', error, info.componentStack)
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
function TestComponent({ showCrash }) {
if (showCrash) {
throw new Error('I am broken');
}
return <p style={{ color: 'white' }}>Test Component</p>
}
export function App() {
const [showCrash, setShowCrash] = useState(false);
return (
<>
<ErrorBoundary fallback={<div>An error was encountered. Please try again later</div>}>
<TestComponent showCrash={showCrash} />
<button onClick={() => setShowCrash(true)}>Show boundary error</button>
</ErrorBoundary>
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment