active link nextjs code example

Example 1: next js active link

import Link from "next/link";
import { useRouter } from "next/router";


export const MyNav = () => {

  const router = useRouter();

  return (
    <ul>
      <li className={router.pathname == "/" ? "active" : ""}>
        <Link href="/">home</Link>
      </li>
      <li className={router.pathname == "/about" ? "active" : ""}>
        <Link href="/about">about</Link>
      </li>
    </ul>
  );
};

Example 2: nextjs active link

import Link from 'next/link';
import { useRouter } from 'next/router';
import React from 'react';

const NavLink = ({ href, children }) => {
    const router = useRouter();

    let className = children.props.className || '';
    if (router.pathname === href) {
        className = `${className} selected`;
    }

    return <Link href={href}>{React.cloneElement(children, { className })}</Link>
}

export default NavLink;