Breadcrumbs
77 lines · 1 file · MIT
Where the page sits: each parent a link, the middle folded away on a phone.
import { Fragment, type ReactNode } from "react";
import { ChevronRight, Ellipsis } from "./icons";
import { cn } from "./cn";
export interface Crumb {
label: string;
/** Where it goes. The last crumb is the current page and takes none. */
href?: string;
/** Set the label in the mono face: a slug or a domain. */
mono?: boolean;
}
/**
* Where the page sits: each parent a link, the current page last and plain.
* On a narrow screen the middle collapses to an ellipsis so the first and
* last stay readable; the full path stays in the markup for a screen reader.
*/
export function Breadcrumbs({
items,
renderLink,
className,
}: {
items: readonly Crumb[];
/** Draw a link with your router's component; a plain anchor by default. */
renderLink?: (crumb: Crumb, children: ReactNode, className: string) => ReactNode;
className?: string;
}) {
const link =
"truncate rounded-sm text-muted transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent [@media(hover:hover)]:hover:text-text";
return (
<nav aria-label="Breadcrumb" className={cn("min-w-0", className)}>
<ol className="flex min-w-0 items-center gap-1.5 text-sm">
{items.map((crumb, index) => {
const last = index === items.length - 1;
const middle = index > 0 && !last;
const text = cn(crumb.mono && "font-mono text-[13px]");
// On a narrow screen a middle crumb and its separator are hidden,
// and one ellipsis stands in for all of them.
const hide = middle && "max-sm:hidden";
return (
<Fragment key={`${crumb.href ?? ""}${crumb.label}`}>
{last && items.length > 2 && (
<>
<li aria-hidden className="flex shrink-0 text-placeholder sm:hidden">
<ChevronRight size={14} />
</li>
<li aria-hidden className="flex shrink-0 text-muted sm:hidden">
<Ellipsis size={14} />
</li>
</>
)}
{index > 0 && (
<li aria-hidden className={cn("flex shrink-0 text-placeholder", hide)}>
<ChevronRight size={14} />
</li>
)}
<li className={cn("flex min-w-0 items-center", hide, last && "text-text")}>
{last || !crumb.href ? (
<span aria-current={last ? "page" : undefined} className={cn("truncate", text)}>
{crumb.label}
</span>
) : renderLink ? (
renderLink(crumb, crumb.label, cn(link, text))
) : (
<a href={crumb.href} className={cn(link, text)}>
{crumb.label}
</a>
)}
</li>
</Fragment>
);
})}
</ol>
</nav>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/breadcrumbs- Category
- Navigation
- Files
- breadcrumbs.tsx