Last active
October 13, 2022 22:18
-
-
Save agamm/6e5c90a86d2769d67718e62daa1d0a00 to your computer and use it in GitHub Desktop.
Nextjs Link component with a redirection delay.
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
// Don't follow this link: unzip.dev (unless you're curious). | |
import { useRouter } from 'next/router' | |
import React from "react"; | |
import { useCallback, useEffect } from "react"; | |
interface LinkProps { | |
/** | |
* The url to send link to | |
*/ | |
href: string; | |
/** | |
* prefetch the url | |
*/ | |
prefetch?: boolean; | |
/** | |
* Delay before redirecting | |
*/ | |
delay?: number; | |
/** | |
* Children components | |
*/ | |
children: React.ReactNode | |
} | |
const Link = ({ | |
href, | |
prefetch = true, | |
delay, | |
children | |
}: LinkProps) => { | |
const router = useRouter(); | |
useEffect(() => { | |
// Prefetch the href if needed | |
if (prefetch) | |
router.prefetch(href) | |
}, []); | |
const onClick : ()=> void = useCallback(() => { | |
setTimeout(() => { | |
router.push({ | |
pathname: href, | |
}) | |
}, delay ?? 0) | |
}, []); | |
return ( | |
<span onClick={onClick}> | |
{children} | |
</span> | |
); | |
} | |
export default Link; | |
/* | |
Usage: | |
Here for example we want to delay so the user will see the animation before redirection. | |
<Link href="/next-step" prefetch={true} delay={100}> | |
<Button onClick={playAnimation}>Go</Button> | |
</Link> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment