Created
January 30, 2024 13:59
-
-
Save adevinwild/49c2a27660dab08b27b826eff8e28b7e to your computer and use it in GitHub Desktop.
A component to override the Next.js 13+ Link App Router component to block internal changes based on a URL parameter.
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 Link from "next/link"; | |
import { useSearchParams } from "next/navigation"; | |
import type { ComponentProps, MouseEvent } from "react"; | |
type Props = ComponentProps<typeof Link> & { | |
message?: string; | |
}; | |
const LinkWithBeforeUnload = (props: Props) => { | |
const searchParams = useSearchParams(); | |
const hasUnsavedChanges = searchParams.get("hasUnsavedChanges") === "true"; | |
const onClick = (e: MouseEvent<HTMLAnchorElement, globalThis.MouseEvent>) => { | |
if (!hasUnsavedChanges) { | |
return; | |
} | |
const shouldContinue = window.confirm( | |
props.message ?? | |
"You have unsaved changes, are you sure you want to leave this page?" | |
); | |
if (!shouldContinue) { | |
e.preventDefault(); | |
return; | |
} | |
}; | |
return ( | |
<Link {...props} onClick={onClick}> | |
{props.children} | |
</Link> | |
); | |
}; | |
export default LinkWithBeforeUnload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment