-
-
Save YutaMoriJP/e38680308454a4416451bf5200da18cc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Turn all HTML <a> elements into client side router links, no special framework-specific <Link> component necessary! | |
| // Example using the Next.js App Router. | |
| import { useRouter } from 'next/navigation'; | |
| import { useEffect } from 'react'; | |
| function useLinkHandler() { | |
| let router = useRouter(); | |
| useEffect(() => { | |
| let onClick = e => { | |
| let link = e.target.closest('a'); | |
| if ( | |
| link && | |
| link instanceof HTMLAnchorElement && | |
| link.href && | |
| (!link.target || link.target === '_self') && | |
| link.origin === location.origin && | |
| !link.hasAttribute('download') && | |
| e.button === 0 && // left clicks only | |
| !e.metaKey && // open in new tab (mac) | |
| !e.ctrlKey && // open in new tab (windows) | |
| !e.altKey && // download | |
| !e.shiftKey && | |
| !e.defaultPrevented | |
| ) { | |
| e.preventDefault(); | |
| router.push(link.href); | |
| } | |
| }; | |
| document.addEventListener('click', onClick); | |
| return () => { | |
| document.removeEventListener('click', onClick); | |
| }; | |
| }, [router]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment