This can be done using the HOC, which parses the pathname from the reactor router and returns matches with it. Although I'm a little more verbose, I think it gives more flexibility and a good readable array of objects for palette configuration.
Breadcrumbs.jsx
import React from 'react'; import { NavLink } from 'react-router-dom'; import { withBreadcrumbs } from 'withBreadcrumbs'; const UserBreadcrumb = ({ match }) => <span>{match.params.userId}</span>; // use match param userId to fetch/display user name const routes = [ { path: 'users', breadcrumb: 'Users' }, { path: 'users/:userId', breadcrumb: UserBreadcrumb}, { path: 'something-else', breadcrumb: ':)' }, ]; const Breadcrumbs = ({ breadcrumbs }) => ( <div> {breadcrumbs.map(({ breadcrumb, path, match }) => ( <span key={path}> <NavLink to={match.url}> // wrap breadcrumb with semantic-ui element {breadcrumb} </NavLink> <span>/</span> </span> ))} </div> ); export default withBreadcrumbs(routes)(Breadcrumbs);
withBreadcrumbs.js
import React from 'react'; import { matchPath, withRouter } from 'react-router'; const renderer = ({ breadcrumb, match }) => { if (typeof breadcrumb === 'function') { return breadcrumb({ match }); } return breadcrumb; }; export const getBreadcrumbs = ({ routes, pathname }) => { const matches = []; pathname .replace(/\/$/, '') .split('/') .reduce((previous, current) => { const pathSection = `${previous}/${current}`; let breadcrumbMatch; routes.some(({ breadcrumb, path }) => { const match = matchPath(pathSection, { exact: true, path }); if (match) { breadcrumbMatch = { breadcrumb: renderer({ breadcrumb, match }), path, match, }; return true; } return false; }); if (breadcrumbMatch) { matches.push(breadcrumbMatch); } return pathSection; }); return matches; }; export const withBreadcrumbs = routes => Component => withRouter(props => ( <Component {...props} breadcrumbs={ getBreadcrumbs({ pathname: props.location.pathname, routes, }) } /> ));
An open source HOC is also available here: https://github.com/icd2k3/react-router-breadcrumbs-hoc
source share