Skip to content

Instantly share code, notes, and snippets.

@remy
Last active April 12, 2024 08:33
Show Gist options
  • Star 78 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save remy/0dde38897d6d660f0b63867c2344fb59 to your computer and use it in GitHub Desktop.
Save remy/0dde38897d6d660f0b63867c2344fb59 to your computer and use it in GitHub Desktop.
Next.js version of `activeClassName` support.
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>
);
@mr9d
Copy link

mr9d commented Jan 16, 2022

Here's my version of ActiveLink for Next.js + TypeScript:

import Link, { LinkProps } from "next/link";
import { NextRouter, useRouter } from "next/router";
import { FC, PropsWithChildren } from "react";

type ActiveLinkProps = LinkProps & {
  activeClassName: string;
  className: string;
};

export const ActiveLink: FC<ActiveLinkProps> = ({ children, ...props }: PropsWithChildren<ActiveLinkProps>) => {
  const router: NextRouter = useRouter();
  const className: string =
    props.className + ((router.pathname === props.href && props.activeClassName) ? " " + props.activeClassName : "");
  return (
    <Link {...props}>
      <a className={className}>{children}</a>
    </Link>
  );
};

Example of usage:

          <ActiveLink href="/" className="menulink" activeClassName="active">
            Home
          </ActiveLink>

The difference is you no longer need <a> tag inside.

Benefits:

  • TypeScript-friendly
  • You no longer need to find child element and its type with Children.only
  • You no longer need to do React.cloneElement
  • You won't forget to put <a> inside anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment