nextjs active navlink with tailwind css example

In this section we will see active navlink in next js using tailwind css. We will see current active link, router active link using NEXT JS and Tailwind CSS.


Tool Use

NEXT JS

Tailwind CSS 3.v


Example 1

Create active navlink in next js with tailwind.

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

export default function Home() {
  const router = useRouter();

  return (
    <nav className="container flex justify-around py-8 mx-auto bg-white">
      <div>
        <h3 className="text-2xl font-medium text-blue-500">LOGO</h3>
      </div>
      <div className="flex space-x-8">
        <Link href="/" passHref>
          <div
            className={`text-sm font-medium ${
              router.pathname === "/"
                ? "border-b-2 border-blue-600"
                : "text-gray-700"
            }`}
          >
            Home
          </div>
        </Link>
        <Link href="/about" passHref>
        <div
            className={`text-sm font-medium ${
              router.pathname === "/about"
                ? "border-b-2 border-blue-600"
                : "text-gray-700"
            }`}
          >
            About
          </div>
        </Link>
        <Link href="/blogs" passHref>
        <div
            className={`text-sm font-medium ${
              router.pathname === "/blogs"
                ? "border-b-2 border-blue-600"
                : "text-gray-700"
            }`}
          >
            Blogs
          </div>
        </Link>
        <Link href="/contact" passHref>
        <div
            className={`text-sm font-medium ${
              router.pathname === "/contact"
                ? "border-b-2 border-blue-600"
                : "text-gray-700"
            }`}
          >
            Contact US
          </div>
        </Link>
      </div>
    </nav>
  );
}
next 13 active nav link with tailwind css

next 13 active nav link with tailwind css


Example 2

Current Active navlink with map function nextjs with tailwind css.

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

export default function Home() {
  const router = useRouter();
  const links = [
    { path: '/', label: 'Home' },
    { path: '/about', label: 'About' },
    { path: '/blogs', label: 'Blogs' },
    { path: '/contact', label: 'Contact' }
  ];
  return (
    <nav className="container flex justify-around py-8 mx-auto bg-white">
      <div>
        <h3 className="text-2xl font-medium text-blue-500">LOGO</h3>
      </div>
      <div className="flex space-x-8">
      {links.map(({ path, label }) => (
        <Link key={path} href={path} passHref>
          <div
            className={`text-sm font-medium ${
              router.pathname === path
                ? "border-b-2 border-blue-600"
                : "text-gray-700"
            }`}
          >
               {label}
          </div>
        </Link>
           ))}
      </div>
    </nav>
  );
}