Created
September 17, 2024 16:51
-
-
Save james2doyle/c1ac00f435312d7db8e851a8b41981bf to your computer and use it in GitHub Desktop.
A React Error Boundary that has some basic styling and functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client'; | |
import { ErrorBoundary } from 'react-error-boundary'; | |
import type { ErrorInfo } from 'react'; | |
import type { ErrorBoundaryProps, FallbackProps } from 'react-error-boundary'; | |
import { Button } from '@components/Button'; | |
const logError = (error: Error, info: ErrorInfo) => { | |
console.error({ error, info }); | |
}; | |
const ErrorFallback: React.FC<FallbackProps & { message?: string }> = ({ | |
message, | |
error, | |
resetErrorBoundary, | |
}) => { | |
return ( | |
<div className="rounded p-4"> | |
<h2 className="mb-2 font-bold text-xl"> | |
Something went wrong{message ? ` in "${message}":` : ':'} | |
</h2> | |
<p className="mb-4">{error.message}</p> | |
<Button | |
variant="primary" | |
onClick={resetErrorBoundary} | |
> | |
Try again | |
</Button> | |
</div> | |
); | |
}; | |
export const MyErrorBoundary: React.FC< | |
React.PropsWithChildren< | |
Omit< | |
ErrorBoundaryProps, | |
'FallbackComponent' | 'onError' | 'fallback' | 'fallbackRender' | |
> | |
> | |
> = ({ children, ...rest }) => { | |
return ( | |
<ErrorBoundary | |
FallbackComponent={undefined} | |
fallbackRender={ErrorFallback} | |
onError={logError} | |
{...rest} | |
> | |
{children} | |
</ErrorBoundary> | |
); | |
}; | |
export default MyErrorBoundary; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment