Last active
March 8, 2024 15:53
-
-
Save kachidk/c7c12c2428b22fef4400cf3d3583c8db to your computer and use it in GitHub Desktop.
How to add styling to an active link in NextJS
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 React, { forwardRef } from "react"; | |
import Link, { LinkProps } from "next/link"; | |
import { useRouter } from "next/router"; | |
interface Props extends React.PropsWithChildren<LinkProps> { | |
href: string; | |
children?: string | JSX.Element; | |
className?: string; | |
activeClassName?: string; | |
exactActiveClassName?: string; | |
style?: React.CSSProperties; | |
activeStyle?: React.CSSProperties; | |
exactActiveStyle?: React.CSSProperties; | |
} | |
function classNames(classes: (string | undefined | null)[]) { | |
return classes.filter(Boolean).join(" "); | |
} | |
export const MyLink = forwardRef((props: Props, ref: any) => { | |
let { | |
href, | |
children, | |
className, | |
activeClassName, | |
exactActiveClassName, | |
style, | |
activeStyle, | |
exactActiveStyle, | |
...rest | |
} = props; | |
const router = useRouter(); | |
return ( | |
<Link href={href}> | |
<span | |
ref={ref} | |
{...rest} | |
className={classNames([ | |
className, | |
router.pathname.includes(href as string) ? activeClassName : null, | |
router.pathname === href ? exactActiveClassName : null, | |
])} | |
style={ | |
router.pathname.includes(href as string) | |
? { ...style, ...activeStyle } | |
: router.pathname === href | |
? { ...style, ...activeStyle, ...exactActiveStyle } | |
: { ...style } | |
} | |
> | |
{children} | |
</span> | |
</Link> | |
); | |
}); | |
MyLink.displayName = "MyLink"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment