Skip to content

Export NavigationGuardProviderContext #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,47 @@ pnpm install next-navigation-guard
)
```

Note that `navGuard.active` is only set for client-side navigation. If the user attempts to close the tab or
manually navigates to a new URL, the navigation guard will fallback to the browser's default confirmation
dialog. This is an inherent limitation of modern browsers.

- Hooking into the library's underlying state

This is an advanced use-case if, for example, you have a special routing setup that prevents you from using
the built-in NextJS router or Link component.

```tsx
import { NavigationGuardProviderContext } from 'next-navigation-guard';

function SpecialLink({ href }: { href: string }) {
const guardMapRef = useContext(NavigationGuardProivderContext);
let guardNavigation: React.MouseEventHandler<HTMLAnchorElement> | undefined = undefined;

for (const guard of guardMapRef.current.values()) {
const { enabled, callback } = guard;
if (!enabled({ to: href, type: 'push' })) continue;

guardNavigation = (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault();
e.stopPropagation();

let confirmed = callback({ to: href, type: 'push' });
if (typeof confirmed === 'boolean') {
confirmed = Promise.resolve(confirmed);
}

void confirmed.then((confirmed) => {
if (!confirmed) return;

guard.enabled = () => false;
window.location.href = href;
});
};
break;
}

return <a href="/" onClick={guardNavigation}>Click Here</a>;
}
```

See working example in example/ directory and its `NavigationGuardToggle` component.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { useNavigationGuard } from "./hooks/useNavigationGuard";
export { NavigationGuardProvider } from "./components/NavigationGuardProvider";
export { NavigationGuardProviderContext } from "./components/NavigationGuardProviderContext";
export type { NavigationGuardCallback as NavigationGuard } from "./types";