DEV Community

Cover image for Add Conditional Style to Link with active route with NextJs and Tailwind
Nadine M. Thêry
Nadine M. Thêry

Posted on

Add Conditional Style to Link with active route with NextJs and Tailwind

Check how to apply a certain format to a link depending on the active route. The typical use case for these is in navbars or menus. Like:

Highlight this link that matches with the route

You can easily use the built-in router from next and apply a certain format.

What I did here is to render my Navbar using an object (in my case "menuItems.js". This is what this file looks like:

import {
  UserIcon,
  ResumeIcon,
  PortfolioIcon,
  HomeIcon,
  BlogIcon,
  ContactIcon,
} from "../components/Icons";

const MenuItems = [
  {
    label: 'Home',
    url: "/",
    icon: <HomeIcon />,
    active: true,
  },
  {
    label: 'About Me',
    url: "/about-me",
    icon: <UserIcon />,
    active: false,
  },
  {
    label: 'Resume',
    url: "/resume",
    icon: <ResumeIcon />,
    active: false,
  },
 {
    label: 'Contact',
    url: "/contact",
    icon: <ContactIcon />,
    active: true,
  },
];

export default MenuItems;

Enter fullscreen mode Exit fullscreen mode

Each of these objects is an item of my Navbar. This allows me to introduce additional information I need to render. Like the icon I want to be displayed, the route it must go to and also if it has to be rendered or not (active: true).

After that, then it's easy to apply a conditional style to an item by checking if the 'url' property of the item matches the current route.

For checking the current route we can use the built-in 'useRouter' hook provided by Next, and the Link object. Just check this by tackling into the asPath property of the router.

Checkout the code:

import MenuItems from "../utils/menuItems";
import Link from "next/link";
import { useRouter } from "next/router";

export const Navbar = () => {
  const router = useRouter();

  return (
    <div className="mt-10">
      {MenuItems.map((item, index) => {
        console.log(item.url);
        return (
          <>
            <Link href={item.url} key={index}>
              <div
                className={`w-24 h-24 text-center border-b-2 border-secondary-500  mt-3 cursor-pointer  ${
                  router.asPath === item.url
                    ? "text-primary-500"
                    : "text-secondary-300"
                }`}
              >
                <div className=" hover:text-primary-500 w-10 mx-auto pb-2">
                  {item.icon}
                </div>

                <p className="text-secondary-300">{item.label}</p>
              </div>
            </Link>
          </>
        );
      })}
    </div>
  );
};

export default Navbar;
Enter fullscreen mode Exit fullscreen mode

This is a simple example of how to apply this to a Navbar, but you can actually use this to conditionally style any object in the page.

Peace and Code
Nadine

Top comments (0)