Created
January 17, 2020 21:51
-
-
Save MrLeebo/0254f2752c1d5d395149366b91faf84f to your computer and use it in GitHub Desktop.
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
<App> | |
<ErrorBoundary> | |
<Routes /> | |
</ErrorBoundary> | |
</App> |
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 from "react"; | |
// Catches rendering errors in child components and shows a generic error alert. | |
// This is sort of the on "unhandledException" of React, ideally the component would | |
// handle its own errors, but if that didn't happen then this will prevent the entire | |
// app from entering an invalid state. | |
export default class ErrorBoundary extends React.Component { | |
state = { error: null }; | |
static getDerivedStateFromError(error) { | |
return { error }; | |
} | |
render() { | |
const { error } = this.state; | |
if (error) { | |
return ( | |
<div> | |
<p>Something went wrong.</p> | |
<p>{error.message}</p> | |
<button onClick={() => this.setState({ error: null })}>Close</button> | |
</div> | |
); | |
} | |
return this.props.children; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment