Adding Dynamic Breadcrumb Navigation in a React Next.js Using App Router

Breadcrumbs are a great way to enhance navigation in a web application by showing users their current location within the site’s hierarchy. In this article, we’ll guide you through adding dynamic breadcrumbs to a React Next.js application using the App Router. We’ll break it down step-by-step, using a reusable component to simplify the process.

Step 1: Create the Breadcrumb Component

First, we’ll create a new breadcrumb component that can be reused across your application. This component will dynamically generate breadcrumb links based on the current URL path.

Component Code: DynamicBreadcrumb.tsx

// /components/DynamicBreadcrumb.tsx
'use client'

import React, { ReactNode } from 'react'
import { usePathname } from 'next/navigation'
import Link from 'next/link'

type BreadcrumbProps = {
    homeElement: ReactNode,
    separator: ReactNode,
    containerClasses?: string,
    listClasses?: string,
    activeClasses?: string,
    capitalizeLinks?: boolean
}

const DynamicBreadcrumb = ({ homeElement, separator, containerClasses, listClasses, activeClasses, capitalizeLinks }: BreadcrumbProps) => {
    const paths = usePathname()
    const pathNames = paths.split('/').filter(path => path)

    return (
        <div>
            <ul className={containerClasses}>
                <li className={listClasses}><Link href={'/'}>{homeElement}</Link></li>
                {pathNames.length > 0 && separator}
                {
                    pathNames.map((link, index) => {
                        let href = `/${pathNames.slice(0, index + 1).join('/')}`
                        let itemClasses = paths === href ? `${listClasses} ${activeClasses}` : listClasses
                        let itemLink = capitalizeLinks ? link[0].toUpperCase() + link.slice(1, link.length) : link
                        return (
                            <React.Fragment key={index}>
                                <li className={itemClasses}>
                                    <Link href={href}>{itemLink}</Link>
                                </li>
                                {pathNames.length !== index + 1 && separator}
                            </React.Fragment>
                        )
                    })
                }
            </ul>
        </div>
    )
}

export default DynamicBreadcrumb

This component uses the usePathname hook from Next.js to get the current URL path. It splits the path into segments and creates a breadcrumb link for each segment. It also supports custom styling and capitalization of breadcrumb links.

Step 2: Use the Breadcrumb Component in a Template

Next, we’ll use this breadcrumb component in a template. This will demonstrate how to include it in a page and customize its appearance.

Usage Example

// /app/template.tsx

import React from 'react'
import DynamicBreadcrumb from '../components/DynamicBreadcrumb'

const Template = () => {
    return (
        <div>
            <NextBreadcrumb
                homeElement={'Home'}
                separator={<span> | </span>}
                activeClasses='text-amber-500'
                containerClasses='flex py-5 bg-gradient-to-r from-purple-600 to-blue-600'
                listClasses='hover:underline mx-2 font-bold'
                capitalizeLinks
            />
            {/* Other content goes here */}
        </div>
    )
}

export default Template

In this example, we import the DynamicBreadcrumb component and use it within a template component. We pass various props to customize the breadcrumb’s appearance:

  • homeElement: The element to display for the home link.
  • separator: The separator element between breadcrumb items.
  • activeClasses: CSS classes for the active breadcrumb item.
  • containerClasses: CSS classes for the breadcrumb container.
  • listClasses: CSS classes for each breadcrumb item.
  • capitalizeLinks: Whether to capitalize the first letter of each breadcrumb link.

Step 3: Add CSS for Styling

You can add custom CSS classes to style the breadcrumb component. Below is an example of CSS that can be used.

CSS Example

/* /styles/globals.css */
.flex {
    display: flex;
}

.py-5 {
    padding-top: 1.25rem;
    padding-bottom: 1.25rem;
}

.bg-gradient-to-r {
    background-image: linear-gradient(to right, var(--tw-gradient-stops));
}

.from-purple-600 {
    --tw-gradient-from: #805ad5;
}

.to-blue-600 {
    --tw-gradient-to: #3182ce;
}

.text-amber-500 {
    color: #d69e2e;
}

.hover\:underline:hover {
    text-decoration: underline;
}

.mx-2 {
    margin-left: 0.5rem;
    margin-right: 0.5rem;
}

.font-bold {
    font-weight: 700;
}

Ensure these classes are available in your project’s global CSS or Tailwind CSS configuration if you’re using Tailwind CSS.

Step 4: Test the Breadcrumb Component

Finally, test the breadcrumb component by navigating through different routes in your Next.js application. Ensure the breadcrumbs update dynamically based on the current URL path.

Conclusion

By following these steps, you can add a dynamic breadcrumb component to your Next.js application using the App Router. This enhances the user experience by providing clear navigation paths. Customize the breadcrumb component to fit your design needs, and enjoy a more navigable and user-friendly application.



Leave a Reply

Your email address will not be published. Required fields are marked *