Created
March 17, 2023 11:45
-
-
Save guidani/970864a5c30540cbdbe942ffa8ce6248 to your computer and use it in GitHub Desktop.
Styling link according to current path.
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 { Url } from "next/dist/shared/lib/router/router"; | |
import Link from "next/link"; | |
import { useRouter } from "next/router"; | |
import { MouseEvent } from "react"; | |
type Props = { | |
children?: React.ReactNode; | |
href: Url | string; | |
}; | |
function ActiveLink({ children, href }: Props) { | |
const router = useRouter(); | |
const style = { | |
marginRight: 10, | |
color: router.asPath === href ? "red" : "black", | |
}; | |
const handleClick = (e: MouseEvent<HTMLAnchorElement, MouseEvent>) => { | |
e.preventDefault(); | |
router.push(href); | |
}; | |
return ( | |
<Link href={href} onClick={(e) => handleClick} style={style}> | |
{children} | |
</Link> | |
); | |
} | |
export default ActiveLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment