openfood/components/layout/breadCrumbs.tsx

55 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-10-14 21:28:06 +02:00
import React, { FC, useMemo } from "react";
2021-10-14 20:42:49 +02:00
import { useRouter } from "next/router";
2021-10-14 21:28:06 +02:00
import { Breadcrumbs, Button, Link as MuiLink } from "@mui/material";
2021-10-14 20:42:49 +02:00
import Link from "next/link";
2021-10-14 21:28:06 +02:00
const getPathAsContinuousLinks = (path: string) => {
const linkPath = path.split("/");
linkPath.shift();
return linkPath.map((path, i) => ({
breadcrumb: path,
href: "/" + linkPath.slice(0, i + 1).join("/"),
}));
};
export const BreadCrumbs: FC = () => {
2021-10-14 20:42:49 +02:00
const router = useRouter();
2021-10-14 21:28:06 +02:00
const breadcrumbs = useMemo(
() => getPathAsContinuousLinks(router.asPath),
[router.asPath]
);
2021-10-14 20:42:49 +02:00
if (!breadcrumbs) {
return null;
}
return (
<Breadcrumbs aria-label="breadcrumb">
<Link href="/" passHref>
<MuiLink
underline="hover"
color={
breadcrumbs.length === 1 && breadcrumbs[0].href == "/"
? "text.primary"
: "inherit"
}
>
home
</MuiLink>
</Link>
{breadcrumbs.map((breadcrumb, i) => (
<Link key={breadcrumb.href} href={breadcrumb.href} passHref>
<MuiLink
underline="hover"
color={i === breadcrumbs.length - 1 ? "text.primary" : "inherit"}
>
{breadcrumb.breadcrumb}
</MuiLink>
</Link>
))}
</Breadcrumbs>
);
};