Created
April 18, 2024 23:40
-
-
Save mokargas/084c3604fa93962ec98664ce62aa0021 to your computer and use it in GitHub Desktop.
Basic error boundary example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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