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:
Install React Router:
If you haven't already, install React Router:
bashnpm install react-router-dom
Create a Breadcrumb Component:
Create a new component named Breadcrumbs.js
:
jsximport 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;
Use the Breadcrumbs Component:
Use the Breadcrumbs
component in your app where you want to display the breadcrumbs navigation:
jsximport 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;
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.
jsximport React from 'react';
const Page1 = () => {
return <div>This is Page 1</div>;
};
export default Page1;
jsximport React from 'react';
const Page2 = () => {
return <div>This is Page 2</div>;
};
export default Page2;
jsximport 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.