Breadcrumbs help users navigate by showing the path to the current page.Here's how to implement them using React Router:
1. Install Dependencies (If Not Installed)
npm install react-router-dom
2. Set Up Routing with Breadcrumbs
App.js
import React from "react";
import { BrowserRouter as Router, Routes, Route, Link, useLocation } from "react-router-dom";
const Home = () => <h2>Home Page</h2>;
const Products = () => <h2>Products Page</h2>;
const ProductDetails = () => <h2>Product Details</h2>;
const Breadcrumbs = () => {
const location = useLocation();
const paths = location.pathname.split("/").filter(path => path);
return (
<nav>
<Link to="/">Home</Link> {paths.length > 0 && " / "}
{paths.map((path, index) => {
const url = `/${paths.slice(0, index + 1).join("/")}`;
return (
<span key={url}>
<Link to={url}> {path} </Link> {index < paths.length - 1 && " / "}
</span>
);
})}
</nav>
);
};
function App() {
return (
<Router>
<Breadcrumbs />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:id" element={<ProductDetails />} />
</Routes>
</Router>
);
}
export default App;