Files
babymonitor/frontend/src/components/ErrorBoundary.tsx
T
2026-04-24 08:02:13 +02:00

46 lines
1.1 KiB
TypeScript

import { Component, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error("ErrorBoundary caught an error", error, errorInfo.componentStack);
}
render() {
if (this.state.hasError) {
return (
this.props.fallback || (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 text-center">
<p className="text-red-600 font-medium">Failed to load this component</p>
<button
onClick={() => this.setState({ hasError: false })}
className="mt-2 text-sm text-red-500 hover:underline"
>
Try again
</button>
</div>
)
);
}
return this.props.children;
}
}