Building a Dynamic Breadcrumbs Component in Next.js
As web applications grow in complexity, providing intuitive navigation becomes crucial. Breadcrumbs, a navigational aid displaying the path to the current page, offer users a clear trail to follow. In this article, we’ll explore the creation of a dynamic breadcrumbs component using Next.js, enhancing user experience and simplifying navigation within your web app.
Setting the Stage: A Client-Side Approach
Our breadcrumbs component operates on the client-side, leveraging Next.js along with the usePathname
hook from next/navigation
. This hook fetches the current page's pathname, serving as the cornerstone for dynamically generating breadcrumb links.
Integrating UI Libraries: Utilizing PrimeReact
While building this component, we’ll incorporate primereact/breadcrumb
from the PrimeReact UI library. This library seamlessly transforms our breadcrumb data into an elegant visual representation. However, it's crucial to note that this approach isn't limited to PrimeReact; it's adaptable to other UI libraries as well.
"use client";
import Link from "next/link";
import { capitalize } from "@/utils/textUtils";
import { usePathname } from "next/navigation";
import { BreadCrumb } from "primereact/breadcrumb";
import { MenuItem } from "primereact/menuitem";
const CommonBreadcrumbs = () => {
const pathname = usePathname();
const segments = pathname.split("/").filter((item) => item !== "");
const home = { icon: "pi pi-home", url: "/" };
const items: MenuItem[] = segments.map((item, index) => {
return {
disabled: index === segments.length - 1,
template: () => (
<Link
key={item}
href={`/${segments.slice(0, index + 1).join("/")}`}
aria-label={`Go to ${capitalize(item)}`}
>
{capitalize(item)}
</Link>
),
};
});
return <BreadCrumb home={home} model={items} />;
};
export default CommonBreadcrumbs;
Lets break it down
const pathname = usePathname();
- The
usePathname
hook fromnext/navigation
in Next.js is used to fetch the current page's pathname.
const segments = pathname.split("/").filter((item) => item !== "");
- The fetched pathname is then split into segments using the
.split("/")
method, creating an array of individual path segments. - The
filter()
method is applied to remove any empty segments resulting from consecutive slashes in the URL.
const items: MenuItem[] = segments.map((item, index) => { ... });
- This code maps over each segment in the
segments
array. - For each segment, it creates an object representing a breadcrumb item.
- The
disabled
property is set totrue
for the last segment to disable the link to the current page (as it's the current location). - The
template
property defines the JSX structure for each breadcrumb link using theLink
component from Next.js. - The
href
attribute for each link is generated by joining segments up to the current index using.slice(0, index + 1).join("/")
, creating the correct URL path. - An
aria-label
is added for accessibility, providing a descriptive label for each breadcrumb link using thecapitalize()
function to make the text more readable.
const capitalize = (str: string) =>
`${str.charAt(0).toUpperCase()}${str.slice(1)}`;
Wrapping Up
Implementing a dynamic breadcrumbs component in Next.js enhances the user journey, providing a seamless navigation experience. As your application scales, this feature remains an invaluable addition, ensuring users can always find their way back.
By following the steps outlined in this article, you’ll empower your Next.js application with a powerful, user-friendly, and dynamic breadcrumbs component.