How To Add Styling To An Active Link In Next.js 14

How To Add Styling To An Active Link In Next.js 14

Next.js, the popular React framework, offers robust features for web development. One crucial aspect is optimizing user experience through well-styled active links. These links indicate the user's current location and enhance navigation.

In earlier versions of Next.js, styling active links has always involved using the React router and so on — but has not been straightforward.

With the introduction of Next.js 13 and 14, you can now use the usePathname Client Component hook to read the current URL's pathname.

'use client';

import { usePathname } from 'next/navigation';

export default function MyClientComponent() {
	const pathname = usePathname();
	return <p>Current pathname: {pathname}</p>;
}

The usePathname function retrieves the current URL's pathname as a string. For instance, if you're on the home page (/) of your Next.js app, it returns "Current pathname: /". If you're on a blog page (/blog), it will display “Current pathname: /blog".

Then you begin to ask, yes this works but how can I add active link styling. Yo! This is very possible.

Suppose you have a Navbar client component that looks like this:

'use client';
import Link from 'next/link';

const NavLinks = [
	{ id: 1, name: 'Home', path: '/' },
	{ id: 2, name: 'Blog', path: '/blog' },
	{ id: 3, name: 'About', path: '/about' },
];

const Navbar = () => {
	return (
		<nav>
			<ul>
				{NavLinks.map((link) => {
					return (
						<li key={link.id}>
							<Link href={link.path}>{link.name}</Link>
						</li>
					);
				})}
			</ul>
		</nav>
	);
};

export default Navbar;

The above component displays a Navbar with three links but when a user navigates across these links, it is difficult to know which page is active via the Navbar.

A way to fix this is to introduce styling for active links so that when the user is navigated to a particular page, the link stays active with a special styling. For example:

To do this, import the usePathname Client Component hook, instantiate it to get the current path, and then create a function to compare paths — if the link path is equal to the pathname from the usePathname hook — style the link as the active link.

'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

const NavLinks = [
	{ id: 1, name: 'Home', path: '/' },
	{ id: 2, name: 'Blog', path: '/blog' },
	{ id: 3, name: 'About', path: '/about' },
];

const Navbar = () => {
	const pathname = usePathname();
	const isActive = (path) => path === pathname;

	return (
		<nav>
			<ul>
				{NavLinks.map((link) => {
					return (
						<li key={link.id}>
							<Link
								href={link.path}
								className={isActive(link.path) ? 'active' : ''}
							>
								{link.name}
							</Link>
						</li>
					);
				})}
			</ul>
		</nav>
	);
};

export default Navbar;

This code iterates through the NavLinks array, rendering each link within an <li> element. The Link component from Next.js is used to handle the navigation. By applying the isActive function as a condition to determine whether a link should have an active class based on the current pathname, you can define custom styling to highlight the active link.

Wrapping Up

Adding a class to an active route is just the beginning of customizing your application's navigation. Once you've implemented the active class, you hold the power to style it in a way that perfectly aligns with your design preferences. This means you can create a unique and distinctive appearance specifically tailored to your active routes.

By manipulating the CSS properties within the 'active' class, you can transform the appearance of the active link to stand out prominently compared to the rest of the navigation links. This might involve changes in text colour, background colour, underlining, or any other visual cues that provide a clear indication of the user's current location within your app.

Remember, the goal here is to enhance user experience by making navigation intuitive and visually engaging. Consider using contrasting colours, bold text, or subtle animations to make the active route easily identifiable, ultimately guiding users seamlessly through your application. The styling possibilities are vast, so feel free to experiment and find the aesthetic that best suits your application's design language and user experience goals.


Joel Olawanle

Written by Joel Olawanle

Joel is a software engineer and teacher. He write's about software development, productivity, and life. He has written over 150 technical content that has helped millions of people all over the world.


Previous Post

Understanding Dynamic Programming With JavaScript

In this article, you'll learn what dynamic programming is, how it works, and how to use it to solve problems with JavaScript.

Next Post

2023, Landed a Full-Time Job, Graduated, Faced Confusions

In this article, you'll learn what dynamic programming is, how it works, and how to use it to solve problems with JavaScript.