Skip to content

Instantly share code, notes, and snippets.

@pH-7
Last active September 28, 2024 15:18
Show Gist options
  • Save pH-7/e32ab25749479ce44f9571be82c90176 to your computer and use it in GitHub Desktop.
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)
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;
};
@pH-7
Copy link
Author

pH-7 commented Sep 28, 2024

Usage:

<LeaveBrowserWarning shouldWarn={hasUnsavedChanges} />

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