Last active
September 28, 2024 15:18
-
-
Save pH-7/e32ab25749479ce44f9571be82c90176 to your computer and use it in GitHub Desktop.
Show warning message when a user attempts to leave the tab (the webpage)
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 { useEffect, useCallback } from 'react'; | |
interface LeaveBrowserWarningProps { | |
shouldWarn: boolean; | |
} | |
/** | |
* Component that displays a warning message when the user attempts to leave the page. | |
* @param {LeaveBrowserWarningProps} props - The component props | |
* @returns {null} | |
*/ | |
export const LeaveBrowserWarning: React.FC<LeaveBrowserWarningProps> = ({ shouldWarn }) => { | |
const handleBeforeUnload = useCallback((event: BeforeUnloadEvent) => { | |
if (shouldWarn) { | |
const message = 'You have unsaved changes. Are you sure you want to leave?'; | |
event.preventDefault(); | |
// Needed for legacy support, e.g., Chrome/Edge < 119 | |
event.returnValue = true; | |
// For modern browsers | |
return message; | |
} | |
}, [shouldWarn]); | |
useEffect(() => { | |
window.addEventListener('beforeunload', handleBeforeUnload); | |
return () => { | |
window.removeEventListener('beforeunload', handleBeforeUnload); | |
}; | |
}, [handleBeforeUnload]); | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: