typescriptintermediate

Error Boundary with Fallback UI

Error boundary class component with customizable fallback UI, retry button, and error reporting.

typescript
import { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback?: (error: Error, reset: () => void) => ReactNode;
  onError?: (error: Error, errorInfo: ErrorInfo) => void;
}

interface State {
  error: Error | null;
}

export class ErrorBoundaryWithFallback extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.props.onError?.(error, errorInfo);
  }

  reset = () => {
    this.setState({ error: null });
  };

  render() {
    if (this.state.error) {
      if (this.props.fallback) {
        return this.props.fallback(this.state.error, this.reset);
      }
      return (
        <div className="p-6 bg-red-500/10 border border-red-500/20 rounded-xl text-center">
          <h3 className="text-red-400 font-medium mb-2">Something went wrong</h3>
          <p className="text-gray-400 text-sm mb-4">{this.state.error.message}</p>
          <button
            onClick={this.reset}
            className="px-4 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500/30"
          >
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

Use Cases

  • Graceful error recovery
  • Widget isolation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.