Last active
October 9, 2024 11:12
-
-
Save adiel/61b22e4ad0d044ea189f744961278643 to your computer and use it in GitHub Desktop.
Sane Link component for Next.js that respects relative URLs
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 InsaneLink from 'next/link'; | |
import { useRouter } from 'next/router'; | |
import React, { ReactNode, useEffect, useState } from 'react'; | |
interface SaneLinkProps { | |
href: string; | |
prefetch? : boolean; | |
children?: ReactNode; | |
className?: string; | |
scroll?: boolean; | |
title?:string; | |
onClick?: (e: any) => void; | |
} | |
const Link: React.FC<SaneLinkProps> = ({ href, prefetch = false, children, className, scroll, title, onClick }) => { | |
const [saneHref, setSaneHref] = useState<string>(href); | |
const router = useRouter(); | |
useEffect(() => { | |
if (!href.startsWith('/')) { | |
let url = new URL(href, 'https://fuck-next-js.com' + router.asPath); | |
setSaneHref(url.pathname); | |
} | |
}, [href, router.asPath]); | |
return <InsaneLink | |
href={saneHref} prefetch={prefetch} className={className} scroll={scroll} title={title} | |
onClick={onClick} | |
> | |
{children} | |
</InsaneLink> | |
}; | |
export default Link; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment