Created
July 26, 2019 11:53
-
-
Save martpie/52e73f396d08babd0edfa8f207dcd9c1 to your computer and use it in GitHub Desktop.
ActiveLink component for Next.js 9
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
/** | |
* Here using data-attributes, but you could use className, or render props as well | |
*/ | |
import React from 'react'; | |
import Link, { LinkProps } from 'next/link'; | |
import { useRouter } from 'next/router'; | |
const ActiveLink: React.FC<LinkProps> = props => { | |
const router = useRouter(); | |
if (typeof props.href === 'object') { | |
throw new TypeError( | |
'[ActiveLink] href props as an object is deprecated since Next.js 9' | |
); | |
} | |
if (typeof props.as === 'object') { | |
throw new TypeError( | |
'[ActiveLink] as props as an object is deprecated since Next.js 9' | |
); | |
} | |
const isActive = router.asPath.startsWith(props.as || props.href); | |
const isExactActive = (props.as || props.href) === router.asPath; | |
return ( | |
<Link {...props}> | |
<a data-is-active={isActive} data-is-exact-active={isExactActive}> | |
{props.children} | |
</a> | |
</Link> | |
); | |
}; | |
export default ActiveLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment