next js active link

To create an active link in Next.js, you can follow these steps:

  1. Import the Link component from the next/link module:
import Link from 'next/link';
  1. Use the Link component to wrap the anchor (<a>) tag that represents the link:
<Link href="/path/to/page">
  <a>Link Text</a>
</Link>

Replace /path/to/page with the actual path to the page you want to link to, and replace Link Text with the text you want to display as the link.

  1. Add the active class to the link when it is active. You can use the useRouter hook from next/router to get information about the current route, such as the pathname. Then, you can conditionally apply the active class based on the current pathname:
import { useRouter } from 'next/router';

function MyLink() {
  const router = useRouter();

  return (
    <Link href="/path/to/page">
      <a className={router.pathname === '/path/to/page' ? 'active' : ''}>
        Link Text
      </a>
    </Link>
  );
}

Replace /path/to/page with the actual path to the page you want to link to, and replace Link Text with the text you want to display as the link.

  1. Style the active class in your CSS to visually indicate that the link is active:
a.active {
  / Your active link styles here /
}

By following these steps, you can create an active link in Next.js that highlights when the corresponding page is active.