Skip to content

Instantly share code, notes, and snippets.

@paulonteri
Created April 4, 2021 17:48
Show Gist options
  • Save paulonteri/de969835118cfbe5f7aaa7fa93458b18 to your computer and use it in GitHub Desktop.
Save paulonteri/de969835118cfbe5f7aaa7fa93458b18 to your computer and use it in GitHub Desktop.
Next.js Breadcrumbs
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
import Link from "next/link";
const convertBreadcrumb = (string) => {
return string
.replace(/-/g, " ")
.replace(/oe/g, "ö")
.replace(/ae/g, "ä")
.replace(/ue/g, "ü")
.toUpperCase();
};
const Breadcrumbs = () => {
const router = useRouter();
const [breadcrumbs, setBreadcrumbs] = useState(null);
useEffect(() => {
if (router) {
const linkPath = router.asPath.split("/");
linkPath.shift();
const pathArray = linkPath.map((path, i) => {
return {
breadcrumb: path,
href: "/" + linkPath.slice(0, i + 1).join("/"),
};
});
setBreadcrumbs(pathArray);
}
}, [router]);
if (!breadcrumbs) {
return null;
}
return (
<nav aria-label="breadcrumbs">
<ol className="breadcrumb">
<li>
<a href="/">HOME</a>
</li>
{breadcrumbs.map((breadcrumb, i) => {
return (
<li key={breadcrumb.href}>
<Link href={breadcrumb.href}>
<a>
{convertBreadcrumb(breadcrumb.breadcrumb)}
</a>
</Link>
</li>
);
})}
</ol>
</nav>
);
};
export default Breadcrumbs;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment