Navigation Guard for Next.js App Router and Pages Router.
npm install @cs198/next-navigation-guardYou use Next.js, and you want to show "You have unsaved changes that will be lost." dialog when user leaves page?
This library is just for you!
https://layerxcom.github.io/next-navigation-guard/
- English Slide
- Japanese Slide
``bash`
npm install next-navigation-guardor
yarn install next-navigation-guardor
pnpm install next-navigation-guard
- App Router: app/layout.tsx
`tsx
${geistSans.variable} ${geistMono.variable}}>`
- Page Router: page/_app.tsx
`tsx`
export default function MyApp({ Component, pageProps }: AppProps) {
return (
);
}
- window.confirm()
`tsx`
useNavigationGuard({ enabled: form.changed, confirm: () => window.confirm("You have unsaved changes that will be lost.") })
- Custom dialog component
`tsx
const navGuard = useNavigationGuard({ enabled: form.changed })
return (
<>
>
)
`
See working example in example/ directory and its NavigationGuardToggle` component.