Table of Contents
If you have a navigation bar in your Next.js website you might want to highlight the active page. In this article we wil see how to highlight an active link in Next.js using css.
This article assumes that you are already having a Next.js app and uses app router.
Creating the Active Link component
Create a file called ActiveLink.tsx
in components folder with the following code:
1"use client";23import React from "react";4import Link from "next/link";5import { usePathname } from "next/navigation";67export const ActiveLink = ({ href, children }) => {8 const pathname = usePathname();9 const isActive = pathname === href;1011 return (12 <Link href={href} className={isActive ? "active" : ""}>13 {children}14 </Link>15 );16};
In the above code, we create a custom Link component where we compare the current URL with the href passed to it. If they are same them we add the class active
to it.
Now let's add some styles.
In global.css
, add the following declarations:
1nav {2 padding: 1rem;3 background-color: #f0f0f0;4}56nav a {7 margin-right: 1rem;8 text-decoration: none;9 color: #333;10}1112nav a.active {13 font-weight: bold;14 color: #0070f3;15}
Creating pages
Now let's create 2 pages About and Contact
1export default function About() {2 return <h1>About Us</h1>;3}
1export default function Contact() {2 return <h1>Contact Us</h1>;3}
Now update the home page with the following code:
1export default function Home() {2 return <h1>Welcome to the Home Page</h1>;3}
Building the nav bar
Now in the layout.js we need to add the nav bar, which will be visible in all the pages.
1import { ActiveLink } from "./components/ActiveLink";2import "./globals.css";3456export default function RootLayout({ children }) {7 return (8 <html lang="en">9 <body>10 <nav>11 <ActiveLink href="/">Home</ActiveLink>12 <ActiveLink href="/about">About</ActiveLink>13 <ActiveLink href="/contact">Contact</ActiveLink>14 </nav>15 <main>{children}</main>16 </body>17 </html>18 );19}
If you run the code now, you should be able to see the currently active link highlighted.
Do follow me on twitter where I post developer insights more often!