Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created April 28, 2022 17:46
Show Gist options
  • Save guillermodlpa/7a7d43ba3153629decdb9a31eb43e3f2 to your computer and use it in GitHub Desktop.
Save guillermodlpa/7a7d43ba3153629decdb9a31eb43e3f2 to your computer and use it in GitHub Desktop.
React Error Boundary (TypeScript), keeping it in a gist for convenience
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