Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

use-react-router-breadcrumbs

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-react-router-breadcrumbs

A hook for displaying and setting breadcrumbs for react router

  • 2.0.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
47K
increased by3.59%
Maintainers
1
Weekly downloads
 
Created
Source

use-react-router-breadcrumbs

Coverage Status

A small (~1.25kb gzip), flexible, hook for rendering breadcrumbs with react-router (5.1 and up).


example.com/user/123 → Home / User / John Doe

If you'd rather use a Higher Order Component, check out react-router-breadcrumbs-hoc

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 use-react-router-breadcrumbs

or

npm i use-react-router-breadcrumbs --save

Usage

const breadcrumbs = useBreadcrumbs()

Examples

Simple

Start seeing generated breadcrumbs right away with this simple example

import useBreadcrumbs from 'use-react-router-breadcrumbs';

const Breadcrumbs = () => {
  const breadcrumbs = useBreadcrumbs();

  return (
    <React.Fragment>
      {breadcrumbs.map(({ breadcrumb }) => breadcrumb)}
    </React.Fragment>
  );
}

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.

import useBreadcrumbs from 'use-react-router-breadcrumbs';

const userNamesById = { '1': 'John' }

const DynamicUserBreadcrumb = ({ match }) => (
  <span>{userNamesById[match.params.userId]}</span>
);

// define custom breadcrumbs for certain routes.
// breadcumbs can be components or strings.
const routes = [
  { path: '/users/:userId', breadcrumb: DynamicUserBreadcrumb },
  { path: '/example', breadcrumb: 'Custom Example' },
];

// map & render your breadcrumb components however you want.
const Breadcrumbs = () => {
  const breadcrumbs = useBreadcrumbs(routes);

  return (
    <>
      {breadcrumbs.map(({
        match,
        breadcrumb
      }) => (
        <span key={match.url}>
          <NavLink to={match.url}>{breadcrumb}</NavLink>
        </span>
      ))}
    </>
  );
};

For the above example...

PathnameResult
/usersHome / Users
/users/1Home / Users / John
/exampleHome / Custom Example

Route config compatibility

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 use-react-router-breadcrumbs.

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:

const breadcrumbs = useBreadcrumbs(routeConfig);

Dynamic breadcrumb components

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:

// UserBreadcrumb.jsx
const PureUserBreadcrumb = ({ firstName }) => <span>{firstName}</span>;

// find the user in the store with the `id` from the route
const mapStateToProps = (state, props) => ({
  firstName: state.userReducer.usersById[props.match.params.id].firstName,
});

export default connect(mapStateToProps)(PureUserBreadcrumb);

// routes = [{ path: '/users/:id', breadcrumb: UserBreadcrumb }]
// example.com/users/123 --> Home / Users / John

Now we can pass this custom redux breadcrumb into the hook:

const breadcrumbs = useBreadcrumbs([{
  path: '/users/:id',
  breadcrumb: UserBreadcrumb
}]);

Similarly, the location object could be useful for displaying dynamic breadcrumbs based on the route's state:

// dynamically update EditorBreadcrumb based on state info
const EditorBreadcrumb = ({ location: { state: { isNew } } }) => (
  <span>{isNew ? 'Add New' : 'Update'}</span>
);

// routes = [{ path: '/editor', breadcrumb: EditorBreadcrumb }]

// upon navigation, breadcrumb will display: Update
<Link to={{ pathname: '/editor' }}>Edit</Link>

// upon navigation, breadcrumb will display: Add New
<Link to={{ pathname: '/editor', state: { isNew: true } }}>Add</Link>

Options

An options object can be passed as the 2nd argument to the hook.

useBreadcrumbs(routes, options);
OptionTypeDescription
disableDefaultsBooleanDisables all default generated breadcrumbs.
excludePathsArray<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

const breadcrumbs = useBreadcrumbs(routes, { disableDefaults: true })

Option 2: Disable individual default breadcrumbs by passing breadcrumb: null in route config:

const routes = [{ path: '/a/b', breadcrumb: null }];

Option 3: Disable individual default breadcrumbs by passing an excludePaths array in the options object

useBreadcrumbs(routes, { excludePaths: ['/', '/no-breadcrumb/for-this-route'] })

Order matters!

... in certain cases. Consider the following:

[
  { path: '/users/:id', breadcrumb: 'id-breadcrumb' },
  { path: '/users/create', breadcrumb: 'create-breadcrumb' },
]

If the user visits example.com/users/create they will see id-breadcrumb because /users/:id will match before /users/create.

To fix the issue above, just adjust the order of your routes:

[
  { path: '/users/create', breadcrumb: 'create-breadcrumb' },
  { path: '/users/:id', breadcrumb: 'id-breadcrumb' },
]

Now, example.com/users/create will display create-breadcrumb as expected, because it will match first before the /users/:id route.

API

BreadcrumbsRoute = {
  path: String
  breadcrumb?: React.ComponentType | React.ElementType | string | null
  // see: https://reacttraining.com/react-router/web/api/matchPath
  matchOptions?: {
    exact?: boolean
    strict?: boolean
    sensitive?: boolean
  }
  // optional nested routes (for react-router config compatibility)
  routes?: BreadcrumbsRoute[],
  // optional props to be passed through directly to the breadcrumb component
  props?: { [x: string]: unknown };
}

Options = {
  // disable all default generation of breadcrumbs
  disableDefaults?: boolean
  // exclude certain paths fom generating breadcrumbs
  excludePaths?: string[]
}

// if routes are not passed, default breadcrumbs will be returned
useBreadcrumbs(routes?: BreadcrumbsRoute[], options?: Options): Array<React.node>

Keywords

FAQs

Package last updated on 10 Jun 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc