Created
February 25, 2023 08:59
-
-
Save sangdth/aa856c7aa9981a1e93a39f7d452a19ec to your computer and use it in GitHub Desktop.
Implementation of an error boundary in React functional component
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
import { useState, useEffect } from 'react'; | |
function ErrorBoundary({ fallback, children }) { | |
const [error, setError] = useState(null); | |
useEffect(() => { | |
if (error) { | |
// log the error or send it to a server | |
console.error(error); | |
} | |
}, [error]); | |
function resetError() { | |
setError(null); | |
} | |
function handleComponentError(error) { | |
setError(error); | |
} | |
if (error) { | |
// render the fallback UI | |
return React.cloneElement(fallback, { resetError }); | |
} | |
return ( | |
// render the children normally | |
<React.Fragment> | |
{React.Children.map(children, child => | |
React.cloneElement(child, { | |
onError: handleComponentError, | |
}) | |
)} | |
</React.Fragment> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment