All Projects → icd2k3 → use-react-router-breadcrumbs

icd2k3 / use-react-router-breadcrumbs

Licence: MIT license
tiny, flexible, hook for rendering route breadcrumbs with react-router v6

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
shell
77523 projects

Projects that are alternatives of or similar to use-react-router-breadcrumbs

froute
Type safe and flexible router for React
Stars: ✭ 31 (-81.76%)
Mutual labels:  router, react-router
React Redux Antdesign Webpack Starter
react + redux + ant design + react-router 4 + webpack 4 starter
Stars: ✭ 44 (-74.12%)
Mutual labels:  router, react-router
React Native Simple Router
A community maintained router component for React Native
Stars: ✭ 266 (+56.47%)
Mutual labels:  router, react-router
smoothr
A custom React router that leverages the Web Animations API and CSS animations.
Stars: ✭ 28 (-83.53%)
Mutual labels:  router, react-router
React Router Native Stack
A stack navigation component for react-router-native
Stars: ✭ 171 (+0.59%)
Mutual labels:  router, react-router
cra-redux-boilerplate
⚛️🔨create-react-app application with redux and another cool libraries to make your life easier.
Stars: ✭ 15 (-91.18%)
Mutual labels:  router, react-router
React Router Page Transition
Highly customizable page transition component for your React Router
Stars: ✭ 531 (+212.35%)
Mutual labels:  router, react-router
React Router Util
Useful components and utilities for working with React Router
Stars: ✭ 320 (+88.24%)
Mutual labels:  router, react-router
Redux First History
🎉 Redux First History - Redux history binding support react-router - @reach/router - wouter
Stars: ✭ 163 (-4.12%)
Mutual labels:  router, react-router
React Redux Graphql Apollo Bootstrap Webpack Starter
react js + redux + graphQL + Apollo + react router + hot reload + devTools + bootstrap + webpack starter
Stars: ✭ 127 (-25.29%)
Mutual labels:  router, react-router
boring-router
A type-safe MobX router with parallel routing support.
Stars: ✭ 74 (-56.47%)
Mutual labels:  router, react-router
Easyrouter
A simple android framework used to route activity or action with url.
Stars: ✭ 164 (-3.53%)
Mutual labels:  hook, router
React Router Breadcrumbs Hoc
tiny, flexible, HOC for rendering route breadcrumbs with react-router v4 & 5
Stars: ✭ 276 (+62.35%)
Mutual labels:  react-router, breadcrumbs
yarr
A React router library enabling the render-as-you-fetch concurrent UI pattern.
Stars: ✭ 97 (-42.94%)
Mutual labels:  router, react-router
Ng2 Breadcrumbs
A breadcrumb service for the Angular 7 router
Stars: ✭ 61 (-64.12%)
Mutual labels:  router, breadcrumbs
React Live Route
📌 An enhanced react-router-v4/5 Route that keeps route alive.
Stars: ✭ 207 (+21.76%)
Mutual labels:  router, react-router
use-route-as-state
Use React Router route and query string as component state
Stars: ✭ 37 (-78.24%)
Mutual labels:  hook, react-router
reactube-client
A clone Youtube Web Player using React Provider Pattern, React Context and Typescript
Stars: ✭ 92 (-45.88%)
Mutual labels:  react-router
qlevar router
Manage you project Routes. Create nested routes. Simply navigation without context to your pages. Change only one sub widget in your page when navigating to new route.
Stars: ✭ 51 (-70%)
Mutual labels:  router
vaktija.ba
Web Site
Stars: ✭ 19 (-88.82%)
Mutual labels:  react-router

use-react-router-breadcrumbs

Coverage Status

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


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


Using an older version of react-router? Check out react-router-breadcrumbs-hoc which is compatible with v4 and v5.


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.
// breadcumbs 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
      }) => (
        <span key={match.pathname}>
          <NavLink to={match.pathname}>{breadcrumb}</NavLink>
        </span>
      ))}
    </>
  );
};

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.
// breadcumbs 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[];
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].