Skip to content

Instantly share code, notes, and snippets.

@Tymek
Last active May 25, 2023 22:38
Show Gist options
  • Save Tymek/df2021b77fcea20cabaef46bbee8b001 to your computer and use it in GitHub Desktop.
Save Tymek/df2021b77fcea20cabaef46bbee8b001 to your computer and use it in GitHub Desktop.
Next.js block navigation on unsaved changes
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
/** Ask for confirmation before changing page or leaving site.
*
* @see https://git.io/JOskG
*/
const useNavigationLock = (
isEnabled = true,
warningText = 'You have unsaved changes – are you sure you wish to leave this page?',
) => {
const router = useRouter();
useEffect(() => {
const handleWindowClose = (e: BeforeUnloadEvent) => {
if (!isEnabled) return;
e.preventDefault();
return (e.returnValue = warningText);
};
const handleBrowseAway = () => {
if (!isEnabled) return;
if (window.confirm(warningText)) return;
router.events.emit('routeChangeError');
throw 'routeChange aborted.';
};
window.addEventListener('beforeunload', handleWindowClose);
router.events.on('routeChangeStart', handleBrowseAway);
return () => {
window.removeEventListener('beforeunload', handleWindowClose);
router.events.off('routeChangeStart', handleBrowseAway);
};
}, [isEnabled]);
};
export default useNavigationLock;
@BossBele
Copy link

React Hook useEffect has missing dependencies: 'router.events' and 'warningText'.

Either include them or remove the dependency array. [react-hooks/exhaustive-deps](facebook/react#14920)

@Gatesvert81
Copy link

Please how do I use It in my js code.

@Lucien950
Copy link

Does not work when window.confirm() is false, still navigates away

@BossBele
Copy link

Please how do I use It in my js code.

function MyComponent() {
  // call the hook
  // you may pass a custom message useNavigationLock(true, 'Don't leave please');
  useNavigationLock();

  return <p>Here's how you use it</p>;
}

@Gatesvert81

@maheenur13
Copy link

maheenur13 commented Apr 3, 2023

I found an issue. When I click the cancel button it clear the states.

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