Create Breadcrumb from URL in Next.js
In websites breadcrumbs are used for easy navigation so that users can find their way around pages easily. They are also used for SEO purposes and to show users the hierarchy of the page more effectively.
Manually creating a breadcrumb is a repetitive task that we need to rethink while following good software development principles. Here we are going to create a component that accepts a path (or URL of the page) as a parameter and we will destructure that path into breadcrumbs.
Let’s start:
Create a component CustomBreadcrumb that takes a path as a parameter. Since the path contains a complete url, we need to break it into pieces. A complete url may look like this https://www.example.com/clothes/mens/casual?q=mount+everest&uact=5
The only part we need for breadcrumbs is the part before ‘?’, after this ‘?’ sign the data are used for many other purposes like query parameters and much more.
How to find the path?
The only part we need for breadcrumbs is after the main url until ‘?’ sign. If we consider the link
https://www.example.com/clothes/mens/casual?q=mount+everest&uact=5
Then we only need /clothes/mens/casual for breadcrumbs and others should be omitted. So, how to get this?
In Next.js, we can use the useRouter hook to find the current path of the page. For breadcrumbs, we use the asPath, which gives the exact form of path that we want, property from useRouter. When using the CustomBreadcrumb component, the path will be as /clothes/mens/casual?q=mount+everest&uact=5. If the url contains ?, we need to remove the part behind this, we must split the string.
Take the first index from the array.
Again, we must split the string using /. Since we have stored the output as pathData, let’s do that here as well.
The array pathData will be like
The first index should be the homepage and the last item should not contain the href link. We are using the lodash function to iterate through the data.
The other important part is to assign href to each breadcrumb. If you could apply your trick we can create a href link for each breadcrumb.
This is done by slicing the pathData and joining it with /, which creates a link like /clothes/mens. Here we have done like
The complete code will be like this.
Photo by Victoria Shes on Unsplash