Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Created May 21, 2023 13:57
Show Gist options
  • Save Avi-E-Koenig/f769d5f5cab8f0bfc344dc51419d1c21 to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/f769d5f5cab8f0bfc344dc51419d1c21 to your computer and use it in GitHub Desktop.
Dynamic React Mui Breadcrumbs
import { Breadcrumbs, Link as MuiLink, Typography } from '@mui/material';
import { Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
type BreadCrumbSegment = { path: string; name: string };
function BreadCrumbs() {
const location = useLocation();
const [routeSegments, setRouteSegments] = useState<BreadCrumbSegment[]>([]);
useEffect(() => {
let cumulativePath = '';
const segments = location.pathname
.split('/')
.filter((s) => s.length)
.map((s) => {
cumulativePath += `/${s}`;
const name = s.replace(/-/g, ' ');
const formattedName = name.charAt(0).toUpperCase() + name.slice(1);
return { path: cumulativePath, name: formattedName };
});
setRouteSegments(segments);
}, [location]);
return (
<Breadcrumbs maxItems={2} separator="›" aria-label="breadcrumb">
{routeSegments.map((segment, key, self) => {
return segment === self[self.length - 1] ? (
<Typography key={key} color="text.primary">
{segment.name}
</Typography>
) : (
<MuiLink component={Link} key={key} to={segment.path} underline="hover" color="inherit">
{segment.name}
</MuiLink>
);
})}
</Breadcrumbs>
);
}
export default BreadCrumbs;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment