Skip to content
next

How to highlight an active link in Next.js

Sep 11, 2024Abhishek EH2 Min Read
How to highlight an active link in Next.js

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.

Create a file called ActiveLink.tsx in components folder with the following code:

components/ActiveLink.jsx
1"use client";
2
3import React from "react";
4import Link from "next/link";
5import { usePathname } from "next/navigation";
6
7export const ActiveLink = ({ href, children }) => {
8 const pathname = usePathname();
9 const isActive = pathname === href;
10
11 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:

global.css
1nav {
2 padding: 1rem;
3 background-color: #f0f0f0;
4}
5
6nav a {
7 margin-right: 1rem;
8 text-decoration: none;
9 color: #333;
10}
11
12nav a.active {
13 font-weight: bold;
14 color: #0070f3;
15}

Creating pages

Now let's create 2 pages About and Contact

about/page.js
1export default function About() {
2 return <h1>About Us</h1>;
3}
contact/page.js
1export default function Contact() {
2 return <h1>Contact Us</h1>;
3}

Now update the home page with the following code:

app/page.js
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";
3
4
5
6export 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.

highlighted about link
highlighted contact us link

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com