Skip to content

Instantly share code, notes, and snippets.

@lancegliser
Created December 2, 2019 03:02
Show Gist options
  • Select an option

  • Save lancegliser/72142d2ec30f32219b53bb837f5ce33f to your computer and use it in GitHub Desktop.

Select an option

Save lancegliser/72142d2ec30f32219b53bb837f5ce33f to your computer and use it in GitHub Desktop.
A basic error boundary component for React that can be imported for reuse. The fallback UI is separated and will need to be created.
import * as React from 'react';
import IErrorBoundary from "./IErrorBoundary";
import ErrorBoundaryFallbackUI from './ErrorBoundaryFallbackUI';
type ErrorBoundaryState = {
error?: Error,
};
/**
* Note that this component can not be refactored using hooks yet.
* @link https://reactjs.org/docs/hooks-faq.html
* "componentDidCatch and getDerivedStateFromError:
* There are no Hook equivalents for these methods yet, but they will be added soon."
*/
export default class ErrorBoundary extends React.Component<IErrorBoundary, ErrorBoundaryState> {
constructor(props: IErrorBoundary) {
super(props);
this.state = {};
}
public static getDerivedStateFromError(error: Error) {
// Update state so the next render will show the fallback UI.
return {
error: error,
};
}
// public componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// You can also log the error to an error reporting service
// logErrorToMyService(error, info); // TODO
// this.state = {
// hasError: true,
// error: error,
// errorInfo: errorInfo
// };
// }
public render() {
if (this.state.error) {
return <ErrorBoundaryFallbackUI error={this.state.error} />;
}
return this.props.children;
}
}
import {ReactNode} from "react";
export default interface IErrorBoundary {
children?: ReactNode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment