-
-
Save gapurov/9afcd0904c57ba684a3c6f2f95e0096e 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