How to implement a breadcrumbs navigation system in React Router



Image not found!!

Implementing a breadcrumbs navigation system in React Router involves using route information to dynamically generate breadcrumb links based on the current route's hierarchy. You can achieve this by utilizing React Router's useRouteMatch hook and building a breadcrumb component that updates based on the current route. Here's how you can implement it:

  1. Install React Router:

    If you haven't already, install React Router:

    bash
    npm install react-router-dom
  2. Create a Breadcrumb Component:

    Create a new component named Breadcrumbs.js:

    jsx
    import React from 'react'; import { Link, useRouteMatch } from 'react-router-dom'; const Breadcrumbs = () => { const match = useRouteMatch(); const pathnames = match.url.split('/').filter((x) => x); return ( <div> {pathnames.map((part, index) => { const routeTo = `/${pathnames.slice(0, index + 1).join('/')}`; const isLast = index === pathnames.length - 1; return isLast ? ( <span key={part}>{part}</span> ) : ( <Link key={part} to={routeTo}> {part} </Link> ); })} </div> ); }; export default Breadcrumbs;
  3. Use the Breadcrumbs Component:

    Use the Breadcrumbs component in your app where you want to display the breadcrumbs navigation:

    jsx
    import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Breadcrumbs from './Breadcrumbs'; import Page1 from './Page1'; import Page2 from './Page2'; import Page3 from './Page3'; const App = () => { return ( <Router> <div> <Breadcrumbs /> <Switch> <Route path="/page1" component={Page1} /> <Route path="/page2" component={Page2} /> <Route path="/page3" component={Page3} /> </Switch> </div> </Router> ); }; export default App;
  4. Define Routes and Components:

    Define your routes and components (Page1, Page2, Page3) as needed. These components can contain any content you want to display for each route.

    jsx
    import React from 'react'; const Page1 = () => { return <div>This is Page 1</div>; }; export default Page1;
    jsx
    import React from 'react'; const Page2 = () => { return <div>This is Page 2</div>; }; export default Page2;
    jsx
    import React from 'react'; const Page3 = () => { return <div>This is Page 3</div>; }; export default Page3;

With these steps, you've implemented a breadcrumbs navigation system in your React Router app. The breadcrumbs dynamically update based on the current route's hierarchy, providing users with a clear navigation path.