Breadcrumb
Breadcrumbs are a simple yet powerful UI component that improves website navigation and user experience.
In this component, we not only render the UI but also handle the logic—extracting segments from the current pathname and generating links dynamically. It's a self-contained solution that's both intuitive and SEO-friendly, ideal for blogs, e-commerce, or documentation sites.
Breadcrumb preview
Please install everything that's required
Before setup and using this component, please install all the required dependencies from this link (if you have never installed).
1. Setup codes
Create a new file utils/url.ts, then paste this code below
js/** * Convert page slug to link text * * Examples: * "ui-components" → "UI Components" * "setup-yarn-in-window" → "Setup Yarn In Window" * * @param slug input slug * @returns text */ export function fromSlug(slug: string): string { return slug .split("-") .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join(" "); }
Crete a new file components/ui/Breadcrumb.tsx, then paste this code below
jsx"use client"; import { ChevronRightIcon, HomeIcon } from "@heroicons/react/20/solid"; import { usePathname } from "next/navigation"; import { ROUTES } from "@/constants/routes"; import { fromSlug } from "@/utils/url"; type BreadcrumbItem = { name: string; href: string; }; export function getBreadcrumbs(pathname: string): BreadcrumbItem[] { const segments = pathname.split("/").filter(Boolean); // Remove first empty element const breadcrumbs = segments.map((segment, index) => { const href = "/" + segments.slice(0, index + 1).join("/"); return { name: fromSlug(decodeURIComponent(segment)), href, }; }); return breadcrumbs; } export default function Breadcrumb() { const pathname = usePathname(); const breadcrumbs = getBreadcrumbs(pathname); return ( <nav aria-label="Breadcrumb" className="flex"> <ol role="list" className="flex items-center space-x-4"> <li> <div> <a href={ROUTES.homePage} className="text-gray-400 hover:text-gray-500"> <HomeIcon aria-hidden="true" className="size-5 shrink-0" /> <span className="sr-only">Home</span> </a> </div> </li> {breadcrumbs.map((page) => ( <li key={page.name}> <div className="flex items-center"> <ChevronRightIcon aria-hidden="true" className="size-5 shrink-0 text-gray-400" /> <a href={page.href} className="ml-4 text-sm font-medium text-gray-500 hover:text-gray-700" > {page.name} </a> </div> </li> ))} </ol> </nav> ); }
2. Usages
Now you can add BreadCrumb component in any Page Layout component like this:
jsximport Breadcrumb from "@/components/Breadcrumb"; ... export async function DocsLayout() { ... return ( <> <div className="min-w-0"> <Breadcrumb /> <article> {children} </article> </div> </> ); }
Now you see he UI which is showing the breadcrumb of current page /components/common-ui/breadcrumb