Created
November 23, 2022 01:53
-
-
Save siddharthcpatel/7b9cb09783990eec9e09404bbd0aa7e8 to your computer and use it in GitHub Desktop.
Active Link Component for Next.js 13+
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 { useRouter } from 'next/router'; | |
import Link from 'next/link'; | |
import React, { Children } from 'react'; | |
const ActiveLink = ({ children, ...props }) => { | |
const router = useRouter(); | |
const child = Children.only(children); | |
let className = child.props.className || ''; | |
if (router.pathname === props.href && props.activeClassName) | |
className = `${className} ${props.activeClassName}`.trim(); | |
delete props.activeClassName; | |
return <Link {...props}>{React.cloneElement(child, { className })}</Link>; | |
}; | |
export default ActiveLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment