Breadcrumb title for dynamic routes
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
I'm building a breadcrumbs component, and I need a way to set the title for dynamic routes based on some value known after fetching the dabase based on the dynamic slug:
the component:
the component:
'use client';
import { Anchor, Breadcrumbs, Text } from '@mantine/core';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import styles from './styles.module.css';
export const BreadCrumbs = () => {
const pathname = usePathname();
const t = useTranslations();
const pathRoutes = pathname.split('/').filter(Boolean);
const crumbList = pathRoutes.map((subPath, idx) => {
const href = '/' + pathRoutes.slice(0, idx + 1).join('/');
const title = isNaN(Number(subPath))
? t(`common.navLinks.${subPath}` as any)
: t('common.itemNumber', {
number: subPath,
});
return {
href,
title,
};
});
const Crumb = ({
href,
last,
text,
}: {
text: string;
href: string;
last: boolean;
}) => {
if (last) return <Text>{text}</Text>;
return (
<Anchor component={Link} href={href}>
{text}
</Anchor>
);
};
if (crumbList.length === 0) return;
return (
<Breadcrumbs
classNames={{
root: styles.root,
separator: styles.separator,
breadcrumb: styles.breadCrumb,
}}
separatorMargin='sm'
>
{crumbList.map((c, idx) => (
<Crumb href={c.href} text={c.title} last={false} key={idx} />
))}
</Breadcrumbs>
);
};
2 Replies
Polar bearOP
Is this approach the most suitable even if the app has more than 8 dynamic routes, and some of the routes have two dynamic segments