Skip to content

Instantly share code, notes, and snippets.

@Maxiviper117
Created January 31, 2025 09:12
Show Gist options
  • Save Maxiviper117/4f106c0982396ad90c2c71c398805b49 to your computer and use it in GitHub Desktop.
Save Maxiviper117/4f106c0982396ad90c2c71c398805b49 to your computer and use it in GitHub Desktop.
Flexible and reusable React error boundary with custom fallback, error logging, and reset functionality.
import { Component, type ReactNode } from "react";
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
resetButtonText?: string;
showResetButton?: boolean;
}
interface ErrorBoundaryState {
hasError: boolean;
error?: Error;
}
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: undefined };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
console.error("ErrorBoundary caught an error:", error, errorInfo);
if (this.props.onError) {
this.props.onError(error, errorInfo);
}
}
resetErrorBoundary = () => {
this.setState({ hasError: false, error: undefined });
};
render() {
const { hasError, error } = this.state;
const {
fallback,
children,
resetButtonText = "Try Again",
showResetButton = true,
} = this.props;
if (hasError) {
return (
<div>
{fallback ? (
fallback
) : (
<>
<h2>Something went wrong</h2>
{error && (
<>
<p>Error type: {error.name}</p>
<p>Message: {error.message}</p>
</>
)}
</>
)}
{showResetButton && (
<button onClick={this.resetErrorBoundary}>
{resetButtonText}
</button>
)}
</div>
);
}
return children;
}
}
export default ErrorBoundary;
@Maxiviper117
Copy link
Author

πŸš€ React Error Boundary with Enhanced Customization

This ErrorBoundary component provides a flexible way to handle runtime errors in React applications.
It supports a custom fallback UI, error logging, custom reset button text, and an option to hide the reset button.


πŸ› οΈ Props Explanation

Prop Name Type Default Description
children ReactNode Required The components wrapped inside the error boundary.
fallback ReactNode undefined A custom error UI to display when an error occurs.
onError (error, errorInfo) => void undefined Callback function for logging errors (e.g., send to monitoring services).
resetButtonText string "Try Again" Text for the reset button.
showResetButton boolean true Controls whether the reset button is visible.

πŸ“Œ Usage Examples

1️⃣ Basic Usage (Default Fallback UI)

<ErrorBoundary>
    <ProblematicComponent />
</ErrorBoundary>

2️⃣ Custom Fallback UI

<ErrorBoundary fallback={<h2>Something went wrong. Please refresh.</h2>}>
    <ProblematicComponent />
</ErrorBoundary>

3️⃣ Logging Errors (Sending to Monitoring Services)

const logError = (error, info) => {
    console.error("Logged Error:", error, info);
    // Send to an external monitoring service
};

<ErrorBoundary onError={logError}>
    <ProblematicComponent />
</ErrorBoundary>

4️⃣ Custom Reset Button Text

<ErrorBoundary resetButtonText="Reload Component">
    <ProblematicComponent />
</ErrorBoundary>

5️⃣ Hide Reset Button

<ErrorBoundary showResetButton={false}>
    <ProblematicComponent />
</ErrorBoundary>

6️⃣ Combine Everything

<ErrorBoundary
    fallback={<h2>Oops! Something went wrong.</h2>}
    onError={(error, info) => console.error("Caught Error:", error, info)}
    resetButtonText="Retry"
    showResetButton={true}
>
    <ProblematicComponent />
</ErrorBoundary>

βœ… Why Use This?

βœ” Prevents full page crashes by isolating errors.
βœ” Provides a better user experience with a retry option.
βœ” Customizable fallback UI and logging for better debugging.
βœ” Fully configurable error boundary for different use cases.


πŸ”— Copy and use this in your React projects! πŸš€

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment