npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-react-router-breadcrumbs

v4.0.1

Published

A hook for displaying and setting breadcrumbs for react router

Downloads

201,662

Readme

Important

As of react-router v6.4 there is an officially supported way of producing breadcrumbs. I recommend using this approach, but if it doesn't cover your specific use case, please let us know in the issues.


Description

Render breadcrumbs for react-router 6 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 objects.

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>
);

const CustomPropsBreadcrumb = ({ someProp }) => <span>{someProp}</span>;

// define custom breadcrumbs for certain routes.
// breadcrumbs can be components or strings.
const routes = [
  { path: "/users/:userId", breadcrumb: DynamicUserBreadcrumb },
  { path: "/example", breadcrumb: "Custom Example" },
  {
    path: "/custom-props",
    breadcrumb: CustomPropsBreadcrumb,
    props: { someProp: "Hi" },
  },
];

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

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

For the above example...

| Pathname | Result | | ------------- | --------------------- | | /users | Home / Users | | /users/1 | Home / Users / John | | /example | Home / Custom Example | | /custom-props | Home / Hi |

Advanced (Declarative Routes)

Same as the example above using Declarative Routing.

import useBreadcrumbs, { createRoutesFromChildren, Route } from 'use-react-router-breadcrumbs';

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

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

const CustomPropsBreadcrumb = ({ someProp }) => (
  <span>{someProp}</span>
);

// define custom breadcrumbs for certain routes.
// breadcrumbs can be components or strings.

// map & render your breadcrumb components however you want.
const BreadcrumbTrail = ({ breadCrumbs }) => {
  return (
    <>
      {breadcrumbs.map(({
        match,
        breadcrumb
      }) => (
        <span key={match.pathname}>
          <NavLink to={match.pathname}>{breadcrumb}</NavLink>
        </span>
      ))}
    </>
  );
};

const GenerateAppRoutes = () => {
  // Full declarative react router support. example: Element, children, Nested Routes
  return (
    <Route path='/users/:userId' breadcrumb={DynamicUserBreadcrumb} element={<ProfilePage/>} />
    <Route path='/example' breadcrumb='Custom Example' >
      <Route path='/' breadcrumb='Custom Example' >
        <ExamplePage/>
      </Route>
    </Route>
    <Route path='/custom-props' breadcrumb={CustomPropsBreadcrumb} props={ someProp: 'Hi' } >
      <CustomPage/>
    </Route>
  )
};

const AppRouter = () => {
  // You could use context to set app Routes and add the breadcrumbs somewhere deeper in the application layout.
  const AppRoutes = GenerateAppRoutes();
  const appRouteObjects = createRoutesFromChildren(AppRoutes);
  const breadCrumbs = useBreadcrumbs(appRouteObjects)
  const GeneratedRoutes = useRoutes(appRouteObjects);
  return (
    <React.StrictMode>
      <Router>
        <BreadcrumbTrail breadCrumbs={breadCrumbs}/>
        <GenerateRoutes/>
      </Router>
    <React.StrictMode>
  )
}

For the above example...

| Pathname | Result | | ------------- | --------------------- | | /users | Home / Users | | /users/1 | Home / Users / John | | /example | Home / Custom Example | | /custom-props | Home / Hi |

Route object compatibility

Add breadcrumbs to your existing route object. 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 routes = [
  {
    path: "/sandwiches",
    element: <Sandwiches />,
  },
];

becomes...

const routes = [
  {
    path: "/sandwiches",
    element: <Sandwiches />,
    breadcrumb: "I love sandwiches",
  },
];

then you can just pass the whole routes right into the hook:

const breadcrumbs = useBreadcrumbs(routes);

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,
  },
]);

You cannot use hooks that rely on RouteContext like useParams, because the breadcrumbs are not in the context, you should use match.params instead:

import type { BreadcrumbComponentType } from "use-react-router-breadcrumbs";

const UserBreadcrumb: BreadcrumbComponentType<"id"> = ({ match }) => {
  return <div>{match.params.id}</div>;
};

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);

| 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

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!

use-react-router-breadcrumbs uses the same strategy as react-router 6 to calculate the routing order.

[
  {
    path: "users",
    children: [
      { path: ":id", breadcrumb: "id-breadcrumb" },
      { path: "create", breadcrumb: "create-breadcrumb" },
    ],
  },
];

If the user visits example.com/users/create they will see create-breadcrumb.

In addition, if the index route and the parent route provide breadcrumb at the same time, the index route provided will be used first:

[
  {
    path: "users",
    breadcrumb: "parent-breadcrumb",
    children: [{ index: true, breadcrumb: "child-breadcrumb" }],
  },
];

If the user visits example.com/users they will see child-breadcrumb.

API

interface BreadcrumbComponentProps<ParamKey extends string = string> {
  key: string;
  match: BreadcrumbMatch<ParamKey>;
  location: Location;
}

type BreadcrumbComponentType<ParamKey extends string = string> =
  React.ComponentType<BreadcrumbComponentProps<ParamKey>>;

interface BreadcrumbsRoute<ParamKey extends string = string>
  extends RouteObject {
  children?: BreadcrumbsRoute[];
  breadcrumb?: BreadcrumbComponentType<ParamKey> | string | null;
  props?: { [x: string]: unknown };
}

interface Options {
  // disable all default generation of breadcrumbs
  disableDefaults?: boolean;
  // exclude certain paths fom generating breadcrumbs
  excludePaths?: string[];
  // optionally define a default formatter for generating breadcrumbs from URL segments
  defaultFormatter?: (string) => string;
}

interface BreadcrumbData<ParamKey extends string = string> {
  match: BreadcrumbMatch<ParamKey>;
  location: Location;
  key: string;
  breadcrumb: React.ReactNode;
}

// if routes are not passed, default breadcrumbs will be returned
function useBreadcrumbs(
  routes?: BreadcrumbsRoute[],
  options?: Options
): BreadcrumbData[];