UI libraries / React InstantSearch / Widgets

This is the React InstantSearch v7 documentation. React InstantSearch v7 is the latest version of React InstantSearch and the stable version of React InstantSearch Hooks.

If you were using React InstantSearch v6, you can upgrade to v7.

If you were using React InstantSearch Hooks, you can still use the React InstantSearch v7 documentation, but you should check the upgrade guide for necessary changes.

If you want to keep using React InstantSearch v6, you can find the archived documentation.

Signature
<Breadcrumb
  attributes={string[]}
  // Optional parameters
  rootPath={string}
  separator={string}
  transformItems={function}
  classNames={object}
  translations={object}
  ...props={ComponentProps<'div'>}
/>
Import
1
import { Breadcrumb } from 'react-instantsearch';

About this widget

<Breadcrumb> is a widget that displays navigation links to see where the current page is in relation to the facet’s hierarchy.

It reduces the number of actions a user needs to take to get to a higher-level page and improves the discoverability of the app or website’s sections and pages. It’s commonly used for websites with lot of data, organized into categories with subcategories.

Requirements

The objects to use in the breadcrumb must follow this structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
  {
    "objectID": "321432",
    "name": "lemon",
    "categories.lvl0": "products",
    "categories.lvl1": "products > fruits"
  },
  {
    "objectID": "8976987",
    "name": "orange",
    "categories.lvl0": "products",
    "categories.lvl1": "products > fruits"
  }
]

It’s also possible to provide more than one path for each level:

1
2
3
4
5
6
7
8
[
  {
    "objectID": "321432",
    "name": "lemon",
    "categories.lvl0": ["products", "goods"],
    "categories.lvl1": ["products > fruits", "goods > to eat"]
  }
]

The attributes provided to the widget must be in attributes for faceting, either on the dashboard) or using attributesForFaceting with the API. By default, the separator is > (with spaces) but you can use a different one by using the separator option.

If there is also a <HierarchicalMenu> on the page, it must follow the same configuration.

You can also create your own UI with useBreadcrumb().

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, Breadcrumb } from 'react-instantsearch';

const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <Breadcrumb
        attributes={[
          'categories.lvl0',
          'categories.lvl1',
          'categories.lvl2'
        ]}
      />
    </InstantSearch>
  );
}

Props

Parameter Description
attributes
type: string[]
Required

An array of attributes to generate the breadcrumb.

1
2
3
4
5
6
7
<Breadcrumb
  attributes={[
    'hierarchicalCategories.lvl0',
    'hierarchicalCategories.lvl1',
    'hierarchicalCategories.lvl2',
  ]}
/>
rootPath
type: string
Optional

The path to use if the first level isn’t the root level.

Make sure to also include the root path in your UI state—for example, by setting initialUiState or calling setUiState().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<InstantSearch
  // ...
  initialUiState={{
    YourIndexName: {
      // breadcrumbs share their UI state with hierarchical menus
      hierarchicalMenu: {
        'hierarchicalCategories.lvl0': ['Audio'],
      },
    },
  }}
>
  <Breadcrumb
    // ...
    rootPath="Audio"
  />
</InstantSearch>
separator
type: string
default: >
Optional

The level separator used in the records.

1
2
3
4
<Breadcrumb
  // ...
  separator=" / "
/>
transformItems
type: (items: object[], metadata: { results: SearchResults }) => object[]

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

In addition, the full results data is available, which includes all regular response parameters, as well as parameters from the helper (for example disjunctiveFacetsRefinements).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const transformItems = (items) => {
  return items.map((item) => ({
    ...item,
    label: item.label.toUpperCase(),
  }));
};

function Search() {
  return (
    <Breadcrumb
      // ...
      transformItems={transformItems}
    />
  );
}
classNames
type: Partial<BreadcrumbClassNames>
Optional

The CSS classes you can override and pass to the widget’s elements. It’s useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.

  • root: The root element of the widget.
  • noRefinementRoot: The root element when there are no refinements.
  • list: The list element.
  • item: Each item element.
  • selectedItem: The selected item element.
  • separator: The separator between items.
  • link: The link of each item.
1
2
3
4
5
6
7
<Breadcrumb
  // ...
  classNames={{
    root: 'MyBreadcrumb',
    item: 'MyBreadcrumbItem MyBreadcrumbItem--subclass'
  }}
/>
translations
type: Partial<BreadcrumbTranslations>
Optional

A dictionary of translations to customize the UI text and support internationalization.

  • rootElementText: The text for the breadcrumb’s starting point (for example, “Home page”).
1
2
3
4
5
6
<Breadcrumb
  // ...
  translations={{
    rootElementText: 'Index',
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

Any <div> prop to forward to the root element of the widget.

1
2
3
4
5
<Breadcrumb
  // ...
  className="MyCustomBreadcrumb"
  title="My custom title"
/>

Hook

React InstantSearch let you create your own UI for the <Breadcrumb> widget with useBreadcrumb(). Hooks provide APIs to access the widget state and interact with InstantSearch.

The useBreadcrumb() Hook accepts parameters and returns APIs.

Usage

First, create your React component:

import { useBreadcrumb } from 'react-instantsearch';

function CustomBreadcrumb(props) {
  const {
    items,
    canRefine,
    refine,
    createURL,
  } = useBreadcrumb(props);

  return <>{/* Your JSX */}</>;
}

Then, render the widget:

<CustomBreadcrumb {...props} />

Parameters

Hooks accept parameters. You can pass them manually, or forward the props from your custom component.

When you provide a function to Hooks, make sure to pass a stable reference to avoid rendering endlessly (for example, with useCallback()). Objects and arrays are memoized; you don’t need to stabilize them.

Parameter Description
attributes
type: string[]
Required

An array of attributes to generate the breadcrumb.

1
2
3
4
5
6
7
const breadcrumbApi = useBreadcrumb({
  attributes: [
    'hierarchicalCategories.lvl0',
    'hierarchicalCategories.lvl1',
    'hierarchicalCategories.lvl2',
  ],
});
rootPath
type: string
Optional

The path to use if the first level isn’t the root level.

Make sure to also include the root path in your UI state—for example, by setting initialUiState or calling setUiState().

1
2
3
4
const breadcrumbApi = useBreadcrumb({
  // ...
  rootPath: 'Audio',
});
separator
type: string
default: " > "
Optional

The level separator used in the records.

1
2
3
4
const breadcrumbApi = useBreadcrumb({
  // ...
  separator: ' / ',
});
transformItems
type: (items: object[], metadata: { results: SearchResults }) => object[]

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

In addition, the full results data is available, which includes all regular response parameters, as well as parameters from the helper (for example disjunctiveFacetsRefinements).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const transformItems = (items) => {
  return items.map((item) => ({
    ...item,
    label: item.label.toUpperCase(),
  }));
};

function Breadcrumb() {
  const breadcrumbApi = useBreadcrumb({
    // ...
    transformItems,
  });

  return <>{/* Your JSX */}</>;
}

APIs

Hooks return APIs, such as state and functions. You can use them to build your UI and interact with React InstantSearch.

Parameter Description
items
type: BreadcrumbItem[]

The list of available options, with each option:

  • label: string: the label of the category or subcategory.
  • value: string: the value of breadcrumb item.
1
2
3
4
type BreadcrumbItem = {
  value: string;
  label: string;
};
canRefine
type: boolean

Indicates if search state can be refined.

refine
type: (value: string | null) => string

Sets the path of the hierarchical filter and triggers a new search.

createURL
type: (value: string | null) => string

Generates a URL of the next state of a clicked item. The special value null is used for the root item of the breadcrumb and returns an empty URL.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import React from 'react';
import { useBreadcrumb } from 'react-instantsearch';

function CustomBreadcrumb(props) {
  const { items, refine, createURL } = useBreadcrumb(props);

  function createOnClick(value) {
    return function onClick(event) {
      if (!isModifierClick(event)) {
        event.preventDefault();
        refine(value);
      }
    };
  }

  return (
    <ul>
      <li>
        <a href={createURL(null)} onClick={createOnClick(null)}>
          Home
        </a>
      </li>

      {items.map((item, index) => {
        const isLast = index === items.length - 1;

        return (
          <li key={index}>
            <span aria-hidden="true">&gt;</span>

            {isLast ? (
              item.label
            ) : (
              <a
                href={createURL(item.value)}
                onClick={createOnClick(item.value)}
              >
                {item.label}
              </a>
            )}
          </li>
        );
      })}
    </ul>
  );
}
Did you find this page helpful?