import Link from './Link'; // our version of link
export default () => (
<header className="Header">
<nav>
<Link activeClassName="active" href="/">
<a className="some-other-class">Home</a>
</Link>
<Link activeClassName="active" href="/about">
<a>About</a>
</Link>
<Link activeClassName="active" href="/contact">
<a>Contact</a>
</Link>
</nav>
</header>
);
Last active
November 2, 2024 23:50
-
-
Save remy/0dde38897d6d660f0b63867c2344fb59 to your computer and use it in GitHub Desktop.
Next.js version of `activeClassName` support.
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
import { withRouter } from 'next/router'; | |
import Link from 'next/link'; | |
import React, { Children } from 'react'; | |
const ActiveLink = ({ router, children, ...props }) => { | |
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 withRouter(ActiveLink); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's my version of
ActiveLink
for Next.js + TypeScript:Example of usage:
The difference is you no longer need
<a>
tag inside.Benefits:
Children.only
React.cloneElement
<a>
inside anymore.