React Router Breadcrumbs HOC
A small (~1.3kb compressed & gzipped), flexible, higher order component for rendering breadcrumbs with react-router 5
example.com/user/123 → Home / User / John Doe
Want to use hooks instead? Try use-react-router-breadcrumbs.
Description
Render breadcrumbs for react-router
however you want!
Features
- Easy to get started with automatically generated breadcrumbs.
- Render, map, and wrap breadcrumbs any way you want.
- Compatible with existing route configs.
Install
yarn add react-router-breadcrumbs-hoc
or
npm i react-router-breadcrumbs-hoc --save
Usage
withBreadcrumbs()(MyComponent);
Examples
Simple
Start seeing generated breadcrumbs right away with this simple example (codesandbox)
import withBreadcrumbs from 'react-router-breadcrumbs-hoc';
const Breadcrumbs = ({ breadcrumbs }) => (
<>
{breadcrumbs.map(({ breadcrumb }) => breadcrumb)}
</>
)
export default withBreadcrumbs()(Breadcrumbs);
Advanced
The example above will work for some routes, but you may want other routes to be dynamic (such as a user name breadcrumb). Let's modify it to handle custom-set breadcrumbs. (codesandbox)
import withBreadcrumbs from 'react-router-breadcrumbs-hoc';
const userNamesById = { '1': 'John' }
const DynamicUserBreadcrumb = ({ match }) => (
<span>{userNamesById[match.params.userId]}</span>
);
const routes = [
{ path: '/users/:userId', breadcrumb: DynamicUserBreadcrumb },
{ path: '/example', breadcrumb: 'Custom Example' },
];
const Breadcrumbs = ({ breadcrumbs }) => (
<div>
{breadcrumbs.map(({
match,
breadcrumb
}) => (
<span key={match.url}>
<NavLink to={match.url}>{breadcrumb}</NavLink>
</span>
))}
</div>
);
export default withBreadcrumbs(routes)(Breadcrumbs);
For the above example...
Pathname | Result |
---|
/users | Home / Users |
/users/1 | Home / Users / John |
/example | Home / Custom Example |
Add breadcrumbs to your existing route config. This is a great way to keep all routing config paths in a single place! If a path ever changes, you'll only have to change it in your main route config rather than maintaining a separate config for react-router-breadcrumbs-hoc
.
For example...
const routeConfig = [
{
path: "/sandwiches",
component: Sandwiches
}
];
becomes...
const routeConfig = [
{
path: "/sandwiches",
component: Sandwiches,
breadcrumb: 'I love sandwiches'
}
];
then you can just pass the whole route config right into the hook:
withBreadcrumbs(routeConfig)(MyComponent);
Dynamic breadcrumbs
If you pass a component as the breadcrumb
prop it will be injected with react-router's match and location objects as props. These objects contain ids, hashes, queries, etc from the route that will allow you to map back to whatever you want to display in the breadcrumb.
Let's use Redux as an example with the match object:
const PureUserBreadcrumb = ({ firstName }) => <span>{firstName}</span>;
const mapStateToProps = (state, props) => ({
firstName: state.userReducer.usersById[props.match.params.id].firstName,
});
export default connect(mapStateToProps)(PureUserBreadcrumb);
Now we can pass this custom redux
breadcrumb into the HOC:
withBreadcrumbs([{
path: '/users/:id',
breadcrumb: UserBreadcrumb
}]);
Similarly, the location object could be useful for displaying dynamic breadcrumbs based on the route's state:
const EditorBreadcrumb = ({ location: { state: { isNew } } }) => (
<span>{isNew ? 'Add New' : 'Update'}</span>
);
<Link to={{ pathname: '/editor' }}>Edit</Link>
<Link to={{ pathname: '/editor', state: { isNew: true } }}>Add</Link>
Options
An options object can be passed as the 2nd argument to the hook.
withBreadcrumbs(routes, options)(Component);
Option | Type | Description |
---|
disableDefaults | Boolean | Disables all default generated breadcrumbs. |
excludePaths | Array<String> | Disables default generated breadcrumbs for specific paths. |
Disabling default generated breadcrumbs
This package will attempt to create breadcrumbs for you based on the route section. For example /users
will automatically create the breadcrumb "Users"
. There are two ways to disable default breadcrumbs for a path:
Option 1: Disable all default breadcrumb generation by passing disableDefaults: true
in the options
object
withBreadcrumbs(routes, { disableDefaults: true })
Option 2: Disable individual default breadcrumbs by passing breadcrumb: null
in route config:
{ path: '/a/b', breadcrumb: null }
Option 3: Disable individual default breadcrumbs by passing an excludePaths
array in the options
object
withBreadcrumbs(routes, { excludePaths: ['/', '/no-breadcrumb/for-this-route'] })
Order matters!
Consider the following route configs:
[
{ path: '/users/:id', breadcrumb: 'id-breadcrumb' },
{ path: '/users/create', breadcrumb: 'create-breadcrumb' },
]
To fix the issue above, just adjust the order of your routes:
[
{ path: '/users/create', breadcrumb: 'create-breadcrumb' },
{ path: '/users/:id', breadcrumb: 'id-breadcrumb' },
]
API
Route = {
path: String
breadcrumb?: String|Component
matchOptions?: {
exact?: Boolean,
strict?: Boolean,
}
}
Options = {
excludePaths?: string[]
disableDefaults?: Boolean
}
withBreadcrumbs(routes?: Route[], options?: Options): HigherOrderComponent
getBreadcrumbs({
routes: Route[],
options: Options,
}): Breadcrumb[]