Created
April 28, 2022 17:46
-
-
Save guillermodlpa/7a7d43ba3153629decdb9a31eb43e3f2 to your computer and use it in GitHub Desktop.
React Error Boundary (TypeScript), keeping it in a gist for convenience
This file contains hidden or 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 { Component, ReactNode } from 'react'; | |
// Error boundaries currently have to be classes. | |
class ErrorBoundary extends Component<{ fallback: ReactNode }> { | |
state = { hasError: false, error: null }; | |
static getDerivedStateFromError(error: Error) { | |
return { | |
hasError: true, | |
error, | |
}; | |
} | |
render() { | |
if (this.state.hasError) { | |
return this.props.fallback; | |
} | |
return this.props.children; | |
} | |
} | |
export default ErrorBoundary; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment