Last active
August 18, 2019 22:01
-
-
Save segunadebayo/c8090fc6a8fabf14e0269b658dc3165b to your computer and use it in GitHub Desktop.
Style active link in NextJS
This file contains hidden or 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
// Using className | |
import React from "react"; | |
import Link from "next/link"; | |
import { useRouter } from "next/router"; | |
const NavLink = ({ children, activeClassName, ...props }) => { | |
const router = useRouter(); | |
const child = React.Children.only(children); | |
// Check if the pathname is equal to the href prop | |
const isActive = router.pathname === props.href | |
let className = child.props.className || ""; | |
if (router.pathname === props.href && props.activeClassName) { | |
className = `${className} ${activeClassName}`.trim(); | |
} | |
return <Link {...props}>{React.cloneElement(child, { className })}</Link>; | |
}; | |
// Using render prop | |
const NavLink = ({ children, ...props }) => { | |
const router = useRouter(); | |
let isActive = router.pathname === props.href; | |
return ( | |
<Link {...props}> | |
{typeof children === "function" ? children(isActive) : children} | |
</Link> | |
); | |
}; | |
// Usage | |
export const SampleLink = ({ href, ...props }) => { | |
return ( | |
<NavLink href={href}> | |
{isActive => ( | |
<a style={{color: isActive ? "red" : "gray"}} {...props} /> | |
)} | |
</NavLink> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment