I'm trying to dynamically generate a Material-UI Breadcrumb control using the React Router DOM Route component.
Unfortunately, even when the Route component isn't a match and doesn't render anything, it gets added as a child to the breadcrumbs, so I get empty separators in my UI.
Here is my current component.
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import MuiLink from '@material-ui/core/Link';
import React, { FC } from 'react';
import { Link, Route } from 'react-router-dom';
const MainBreadcrumbs: FC = () => (
<Breadcrumbs>
<Route path="/" render={() => (<MuiLink component={Link} to="/">Home</MuiLink>)} />
<Route path="/jobs" render={() => (<MuiLink component={Link} to="/jobs">Jobs</MuiLink>)} />
<Route path="/jobs/:jobId" render={route => (<MuiLink component={Link} to={`/jobs/${route.match.params.jobId}`}>Job</MuiLink>)} />
<Route path="/jobs/:jobId/steps/:stepIndex" render={route => (<MuiLink component={Link} to={`/jobs/${route.match.params.jobId}/${route.match.params.stepIndex}`}>Step</MuiLink>)} />
</Breadcrumbs>
)
export default MainBreadcrumbs;
This results in a component that looks like Home / / / when on the homepage.
Below is a possible way to do this using the useRouteMatch hook:
import React from "react";
import Breadcrumbs from "@material-ui/core/Breadcrumbs";
import { Link, useRouteMatch } from "react-router-dom";
import MuiLink from "@material-ui/core/Link";
export default function SimpleBreadcrumbs() {
const homeMatches = useRouteMatch("/");
const jobsMatches = useRouteMatch("/jobs");
const jobMatches = useRouteMatch("/jobs/:jobid");
const stepMatches = useRouteMatch("/jobs/:jobid/:stepIndex");
return (
<>
<Breadcrumbs>
{homeMatches && (
<MuiLink component={Link} to="/">
Home
</MuiLink>
)}
{jobsMatches && (
<MuiLink component={Link} to="/jobs">
Jobs
</MuiLink>
)}
{jobMatches && (
<MuiLink component={Link} to={`/jobs/${jobMatches.params.jobid}`}>
Job {jobMatches.params.jobid}
</MuiLink>
)}
{stepMatches && (
<MuiLink
component={Link}
to={`/jobs/${jobMatches.params.jobid}/${
stepMatches.params.stepIndex
}`}
>
Step {stepMatches.params.stepIndex}
</MuiLink>
)}
</Breadcrumbs>
<Link to="/">Go to Home</Link>
<br />
<Link to="/jobs">Go to Jobs</Link>
<br />
<Link to="/jobs/123/abc">Go to Job 123, step abc</Link>
<br />
</>
);
}
I did an example for you: https://codesandbox.io/s/material-demo-ys532
EDITED: So I choose to go with conditional rendering, it may look ugly on the code but you can abstract it by making a component BreadCrumbRoute and give all of these as props and it will look as clear as with Route :) I started building it check code sandbox, you can finish it by yourself :V---
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With