Skip to content

Instantly share code, notes, and snippets.

@abinavseelan
Last active October 30, 2020 20:44
Show Gist options
  • Save abinavseelan/e278d9c5f39064a21bf9b3174f40d8a5 to your computer and use it in GitHub Desktop.
Save abinavseelan/e278d9c5f39064a21bf9b3174f40d8a5 to your computer and use it in GitHub Desktop.
ErrorBoundary
import React from 'react';
class ErrorBoundary extends React.Component {
constructor() {
super();
this.state = {
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError() {
return { error: true };
}
componentDidCatch(error, info) {
this.setState({
error,
errorInfo: info
});
}
render() {
const { error, errorInfo } = this.state;
const { children } = this.props;
if (error) {
return (
<React.Fragment>
<h1>Something went wrong!</h1>
{
__DEV__
? (
// show more details only when in development
<details>
<pre>{error && error.toString()}</pre>
<br />
<pre>{errorInfo && errorInfo.componentStack}</pre>
</details>
)
: (
null
)
}
</React.Fragment>
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment