Breadcrumbs from the Pathname
Medium · Routing
Breadcrumbs ("Home / Blog / My First Post") are usually built from the current URL, for example with usePathname() in a client component. Write the helper that turns a pathname into crumbs.
Write breadcrumbs(pathname, labels) that returns an array of { label, href }:
- The first crumb is always { label: "Home", href: "/" }.
- Every URL segment adds one crumb. Its href is the path up to and including that segment (/docs, then /docs/api, ...).
- The label comes from labels[segment] when it exists. Otherwise decode the segment with decodeURIComponent and title-case it: split on - and capitalize the first letter of each word ("my-first-post" becomes "My First Post").
- Ignore empty segments, so a trailing slash or // changes nothing. Hrefs keep the segment exactly as it appears in the URL (not decoded).
- The last crumb is the current page, so its href is null. For "/" the result is just [{ label: "Home", href: null }].
Next: Match Dynamic Segments