Dynamic Breadcrumb Navigation with React Router v6

dynamic breadcrumb navigation React

React Dynamic Breadcrumbs, Certainly! Creating a dynamic breadcrumb navigation using React Router v6 can enhance the user experience by providing a clear indication of the current page within a nested route structure. And at certain point if they want to go back to any parent page they can directly go back using breadcrumb navigation link so over all it make the great user behaviour. Breadcrumb is so important in case if you have more then 2 pages / steps or more nested pages and which is very common.

When it comes to developing React Dynamic breadcrumbs for each and every page that could cause lot of work and some other issues as well, so dynamically creation of breadcrumb navigation is most prefered and recommended way.

React Dynamic Breadcrumbs
Dynamic breadcrumb react router

What is UseMatches :

It gives the details of the current match route. And Most Important part to create Dynamic Breadcrumbs in react

import { useMatches } from "react-router-dom";

function SomeComponent() {
  const matches = useMatches();
  // [match1, match2, ...]
}

A `match` has following properties :

{
  // id of route
  id,

  // the portion of the URL the route matched
  pathname,

  // the data from the loader
  data,

  // the parsed params from the URL
  params,

  // the <Route handle> with any app specific data, Make note on this Property
  handle,
};

handle is the most important property to make the dynamic routing

Read More about React Basics concept

What is createBrowserRouter :

It is the new way of making the routers for a react project and assign the apropriate element to it. Let’s have a look on what offical documents says :

This is the recommended router for all React Router web projects. It uses the DOM History API to update the URL and manage the history stack.

So overall CreateBrowserRouter is a new way to describe the routes of the application and benifit of using createBrowserRouter is application knows all about routes prerior to page render so it process some logical operations if needed. Sample code example of createBrouwserRouter:

import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";
const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    loader: rootLoader,
    handle={{
      // you can put whatever you want on a route handle
      // here we use "crumb" and return some elements,
      // this is what we'll render in the breadcrumbs
      // for this route
      crumb: () => <Link to="/">Home</Link>,
    }}
    children: [
      {
        path: "team",
        element: <Team />,
        loader: teamLoader,
        handle={{
        crumb: (data) => <span>{data.breadcrumbLabel}</span>,
      }}
      },
    ],
  },
]);
<RouterProvider router={router} />

To read more about react router createReactBrowser

React Dynamic Breadcrumbs :

SetUp Breadcrumb React Project:

Create a new React project using Create React App or your preferred method.

npx create-react-app dynamic-breadcrumbs
cd dynamic-breadcrumbs

Install React Router v6.

npm install react-router-dom

Now create the following react components using react router to generate dynamic breadcrumb navigation

Now we can make a component which will use the above router code to make the dynamic breadcrumb navigation, code will look like below

function Breadcrumbs() {
  let matches = useMatches();
  let crumbs = matches
    // first get rid of any matches that don't have handle and crumb
    .filter((match) => Boolean(match.handle?.crumb))
    // now map them into an array of elements, passing the loader
    // data to each one
    .map((match) => match.handle.crumb(match.data));

  return (
    <ol>
      {crumbs.map((crumb, index) => (
        <li key={index}>{crumb}</li>
      ))}
    </ol>
  );
}

Good thing is this will work any level of nested routes and will create breadcrumb navigation for that, now we can use above component in layout or root level component which is going to be used in entire react application. For more details have a look on useMataches react hook.

Using older version of react router :

Implementing Dynamic Breadcrumbs:

Explain the process of creating a dynamic breadcrumb component that updates based on the current route.

Step 1: Create a Breadcrumb Component

Create a new file, Breadcrumb.js, and define the Breadcrumb component. This component will use the useRoutes hook from React Router v6 to get the current route and generate breadcrumbs.

// Breadcrumb.js
import React from 'react';
import { Link, useRoutes } from 'react-router-dom';

const Breadcrumb = () => {
const routes = useRoutes(); // Get the current route

// Your breadcrumb rendering logic here

return (

{/* Render breadcrumb links dynamically */}
);
};

export default Breadcrumb;

Step 2: Integrate Breadcrumb Component

Integrate the Breadcrumb component into your main application. Import and render it in the layout where you want the breadcrumbs to appear.

// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Breadcrumb from './Breadcrumb';

// Define your routes here

const App = () => {
  return (
    <Router>
      <Routes>
        {/* Define your routes */}
      </Routes>
      <Breadcrumb />
    </Router>
  );
};

export default App;

Step 3: Dynamically Update Breadcrumbs

Inside the Breadcrumb component, use the route information obtained from useRoutes to dynamically generate breadcrumb links.

// Breadcrumb.js
import React from 'react';
import { Link, useRoutes } from 'react-router-dom';

const Breadcrumb = () => {
  const routes = useRoutes();

  // Extract breadcrumb data from the route
  const breadcrumbs = routes?.filter((route) => route.path !== '*' && route.element.props?.breadcrumb);

  return (
    <div>
      {breadcrumbs &&
        breadcrumbs.map((breadcrumb, index) => (
          <span key={index}>
            <Link to={breadcrumb.props.to}>{breadcrumb.props.breadcrumb}</Link>
            {index < breadcrumbs.length - 1 && ' / '}
          </span>
        ))}
    </div>
  );
};

export default Breadcrumb;

Usage Example:

In your route definitions, add a breadcrumb prop to each route with the desired breadcrumb text.

// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Breadcrumb from './Breadcrumb';
import Home from './Home';
import About from './About';
import Contact from './Contact';

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} breadcrumb="Home" />
        <Route path="/about" element={<About />} breadcrumb="About" />
        <Route path="/contact" element={<Contact />} breadcrumb="Contact" />
      </Routes>
      <Breadcrumb />
    </Router>
  );
};

export default App;

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.