Line data Source code
1 : import * as React from 'react';
2 :
3 : interface Props {
4 : /// What to show instead of the children that failed to render
5 : fallback: (error: unknown) => React.ReactNode;
6 : onError?: (error: unknown, info: React.ErrorInfo) => void;
7 : children: React.ReactNode;
8 : }
9 :
10 : interface State {
11 : failure: { error: unknown } | null;
12 : }
13 :
14 : /// Show a fallback when the children fail to render. Without a boundary, React unmounts the whole page.
15 : /// It catches errors of rendering and effects, not the ones of event handlers or promises.
16 : /// Give it a new key to render the children again.
17 1 : export class ErrorBoundary extends React.Component<Props, State> {
18 1 : state: State = { failure: null };
19 :
20 1 : static getDerivedStateFromError(error: unknown): State {
21 1 : return { failure: { error } };
22 1 : }
23 :
24 1 : componentDidCatch(error: unknown, info: React.ErrorInfo): void {
25 1 : this.props.onError?.(error, info);
26 1 : }
27 :
28 1 : render(): React.ReactNode {
29 1 : const { failure } = this.state;
30 1 : return failure != null ? this.props.fallback(failure.error) : this.props.children;
31 1 : }
32 1 : }
|