I am trying to make a dynamic breadcrumb component with custom values in Nextjs 13.
Let’s say I have the route: /dashboard/[tenant]/[invoice]/editor/abcd
.
Currently, I do an API call and populate [tenant]
and [invoice]
with custom names in my Breadcrumb component
; E.g the name of the tenant and document instead of the id’s.
Now I would like to render a link for [invoice]
and ‘editor’ and ‘abcd’ which are all pages, except for [tenant]
.
How can I distinct between a slug that is a page and a slug that isn’t a page?
I know for example that ‘abcd’ is a page because it is the end of the url. But I would not know that for ‘editor’.
I tried using the useParams
hook but that only returns the values in the URL of course.
2
Answers
You can create a page as
/dashboard/invoice/[invoice]/
and populate the page with the invoice details.Change your editor call to
/dashboard/editor/[tenant]/[invoice]
Alternatively, if you insist on your paths, you can name your tenants and invoice with specific string e.g. tenant-1234, invoice-1234, then in /dashboard/[pid], you can check your pid for the tenant or invoice string and generate the associated component. Though, that’s more work than necessary.
In Next.js 13, you can use the
useRouter
hook to get information about the current route, including the path and query parameters. To determine if a part of the slug corresponds to a page, you can compare it against your known routes. Here’s how you can do it:useRouter
hook fromnext/router
:useRouter
hook to get information about the current route, and then extract the slug from it. You can split the slug into its parts using the/
delimiter:In the code above, we split the slug into its parts, iterate through them, and check if each part is in the
knownRoutes
array. If it is, we render a link for that part; otherwise, we display it as text. This way, you can distinguish between slugs that correspond to pages and those that don’t.