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
<RefinementList
  attribute={string}
  // Optional parameters
  operator={'and' | 'or'}
  limit={number}
  showMore={boolean}
  showMoreLimit={number}
  searchable={boolean}
  searchablePlaceholder={string}
  sortBy={string[] | function}
  escapeFacetValues={boolean}
  transformItems={function}
  classNames={object}
  translations= {object}
  ...props={ComponentProps<'div'>}
/>
Import
1
import { RefinementList } from 'react-instantsearch';

About this widget

<RefinementList> is a widget that lets users filter the dataset using multi-select facets.

A refinement list only displays the most relevant facet values for the current search context. The sortBy option only affects how the facets are ordered, not which facets are returned.

The widget also implements search for facet values, which provides a mini search inside the facet values. This helps users find uncommon facet values.

You need to add the provided attribute to the attributes for faceting, either on the dashboard or using attributesForFaceting with the API.

When using the searchable prop, you also need to make the attribute searchable using the dashboard or using the searchable modifier of attributesForFaceting with the API.

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

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, RefinementList } from 'react-instantsearch';

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

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <RefinementList attribute="brand" />
    </InstantSearch>
  );
}

Props

Parameter Description
attribute
type: string
Required

The name of the attribute in the records.

To avoid unexpected behavior, you can’t use the same attribute prop in a different type of widget.

1
<RefinementList attribute="categories" />
operator
type: 'and'|'or'
default: 'or'
Optional

How the facets are combined.

  • 'or': Returns results matching any of the selected values.
  • 'and': Returns results matching all selected values.
1
2
3
4
<RefinementList
  // ...
  operator="and"
/>
limit
type: number
default: 10
Optional

How many facet values to retrieve.

When you set showMore and showMoreLimit, this is the number of facet values to display before clicking the Show more button.

1
2
3
4
<RefinementList
  // ...
  limit={5}
/>
showMore
type: boolean
default: false
Optional

Whether to display a button that expands the number of items.

1
2
3
4
<RefinementList
  // ...
  showMore={true}
/>
showMoreLimit
type: number
Optional

The maximum number of items to display if the widget is showing more items.

1
2
3
4
<RefinementList
  // ...
  showMoreLimit={20}
/>
searchable
type: boolean
default: false
Optional

Whether to add a search input to let users search for more facet values.

You need to make the attribute searchable using the dashboard) or using the searchable modifier of attributesForFaceting with the API.

In some situations, refined facet values might not be present in the data returned by Algolia. Read the FAQ to get more information and adjust your configuration.

1
2
3
4
<RefinementList
  // ...
  searchable={true}
/>
searchablePlaceholder
type: string
Optional

The value of the search input’s placeholder.

1
2
3
4
<RefinementList
  // ...
  searchablePlaceholder="Search our products"
/>
sortBy
type: string[] | (a: FacetValue, b: FacetValue) => number
default: ["isRefined", "count:desc", "name:asc"], or `facetOrdering` if set
Optional

How to sort refinements. Must be one or more of the following strings:

  • "count" (same as "count:desc")
  • "count:asc"
  • "count:desc"
  • "name" (same as "name:asc")
  • "name:asc"
  • "name:desc"
  • "isRefined" (same as "isRefined:asc")
  • "isRefined:asc"
  • "isRefined:desc"

You can also use a sort function that behaves like the standard Javascript compareFunction.

When you don’t set this parameter, and you’ve set facetOrdering for this facet in renderingContent, facets are sorted using facetOrdering and use the default order as a fallback.

In some situations, refined facet values might not be present in the data returned by Algolia. Read the FAQ to get more information and adjust your configuration.

1
2
3
4
<RefinementList
  // ...
  sortBy={['count:desc', 'name:asc']}
/>
escapeFacetValues
type: boolean
default: true
Optional

Escapes the content of the facet values returned by Algolia.

When using this parameter, the highlighting tags are always mark.

1
2
3
4
<RefinementList
  // ...
  escapeFacetValues={false}
/>
transformItems
type: (items: object[], metadata: { results: SearchResults }) => object[]
Optional

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 Algolia search 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 (
    <RefinementList
      // ...
      transformItems={transformItems}
    />
  );
}
classNames
type: Partial<RefinementListClassNames>
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.
  • searchBox: The search box element.
  • noResults: The root element of the widget when there are no results.
  • list: The list element.
  • item: Each item element.
  • selectedItem: Each selected item element.
  • label: The label of each item.
  • checkbox: The checkbox of each item.
  • labelText: The text element of each label.
  • count: The count of each item.
  • showMore: The “Show more” button.
  • disabledShowMore: The disabled “Show more” button.
1
2
3
4
5
6
7
<RefinementList
  // ...
  classNames={{
    root: 'MyCustomRefinementList',
    searchBox: 'MyCustomRefinementListSearchBox MyCustomRefinementListSearchBox--subclass',
  }}
/>
translations
type: Partial<RefinementListTranslations>
Optional

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

  • submitButtonTitle: The submit button title of the search box.
  • resetButtonTitle: The reset button title search box.
  • noResultsText: The text to display when searching for facets returns no results.
  • showMoreButtonText: The text for the “Show more” button.
1
2
3
4
5
6
7
8
9
10
11
12
13
<RefinementList
  // ...
  searchable
  showMore
  translations={{
    submitButtonTitle: 'Submit',
    resetButtonTitle: 'Reset',
    noResultsText: 'No brands matching your query.',
    showMoreButtonText({ isShowingMore }) { 
      return isShowingMore ? 'Show less brands' : 'Show more brands';
    },
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

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

1
2
3
4
5
<RefinementList
  // ...
  className="MyCustomRefinementList"
  title="My custom title"
/>

Hook

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

The useRefinementList() Hook accepts parameters and returns APIs.

Usage

First, create your React component:

import { useRefinementList } from 'react-instantsearch';

function CustomRefinementList(props) {
  const {
    items,
    hasExhaustiveItems,
    createURL,
    refine,
    sendEvent,
    searchForItems,
    isFromSearch,
    canRefine,
    canToggleShowMore,
    isShowingMore,
    toggleShowMore,
  } = useRefinementList(props);

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

Then, render the widget:

<CustomRefinementList {...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
attribute
type: string
Required

The name of the attribute in the records.

To avoid unexpected behavior, you can’t use the same attribute prop in a different type of widget.

1
2
3
const refinementListApi = useRefinementList({
  attribute: 'categories',
});
operator
type: "and"|"or"
default: "or"
Optional

How the filters are combined together.

  • "or": apply an OR between all selected values.
  • "and": apply an AND between all selected values.
1
2
3
4
const refinementListApi = useRefinementList({
  // ...
  operator: 'and',
});
limit
type: number
default: 10
Optional

How many facet values to retrieve.

When you set showMore and showMoreLimit, this is the number of facet values to display before clicking the Show more button.

1
2
3
4
const refinementListApi = useRefinementList({
  // ...
  limit: 5,
});
showMore
type: boolean
default: false
Optional

Whether to display a button that expands the number of items.

1
2
3
4
const refinementListApi = useRefinementList({
  // ...
  showMore: true,
});
showMoreLimit
type: number
Optional

The maximum number of items to display if the widget is showing more items.

1
2
3
4
const refinementListApi = useRefinementList({
  // ...
  showMoreLimit: 20,
});
sortBy
type: string[] | (a: FacetValue, b: FacetValue) => number
default: ["isRefined", "count:desc", "name:asc"], or `facetOrdering` if set
Optional

How to sort refinements. Must be one or more of the following strings:

  • "count" (same as "count:desc")
  • "count:asc"
  • "count:desc"
  • "name" (same as "name:asc")
  • "name:asc"
  • "name:desc"
  • "isRefined" (same as "isRefined:asc")
  • "isRefined:asc"
  • "isRefined:desc"

You can also use a sort function that behaves like the standard Javascript compareFunction.

When you don’t set this parameter, and you’ve set facetOrdering for this facet in renderingContent, facets are sorted using facetOrdering and use the default order as a fallback.

In some situations, refined facet values might not be present in the data returned by Algolia. Read the FAQ to get more information and adjust your configuration.

1
2
3
4
const refinementListApi = useRefinementList({
  // ...
  sortBy: ['count:desc', 'name:asc'],
});
escapeFacetValues
type: boolean
default: true
Optional

Escapes the content of the facet values returned by Algolia.

When using this parameter, the highlighting tags are always mark.

1
2
3
4
const refinementListApi = useRefinementList({
  // ...
  escapeFacetValues: false,
});
transformItems
type: (items: object[], metadata: { results: SearchResults }) => object[]
Optional

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 RefinementList() {
  const refinementListApi = useRefinementList({
    // ...
    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: RefinementListItem[]

The list of filtering values returned by Algolia.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type RefinementListItem = {
  /**
   * The value of the refinement list item.
   */
  value: string;
  /**
   * Human-readable value of the refinement list item.
   */
  label: string;
  /**
   * Human-readable value of the searched refinement list item.
   */
  highlighted?: string;
  /**
   * Number of matched results after refinement is applied.
   */
  count: number;
  /**
   * Indicates if the list item is refined.
   */
  isRefined: boolean;
};
hasExhaustiveItems
type: boolean

Whether the results are exhaustive.

createURL
type: (value: string) => string

Creates the next state URL of a selected refinement.

refine
type: (value: string) => string

Applies the selected refinement.

sendEvent
type: (eventType: string, facetValue: string, eventName?: string) => void

Sends an event to the Insights middleware.

searchForItems
type: (query: string) => void

Searches for values in the list.

isFromSearch
type: boolean

Whether the values are from an index search.

canRefine
type: boolean

Whether a refinement can be applied.

canToggleShowMore
type: boolean

Whether the Show more button can be activated, meaning there are enough additional items to display, or already displaying over the limit items.

isShowingMore
type: boolean

Whether the menu is displaying all the menu items.

toggleShowMore
type: () => void

Toggles the number of values displayed between limit and showMoreLimit.

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
import React from 'react';
import { useRefinementList } from 'react-instantsearch';

function CustomRefinementList(props) {
  const {
    items,
    refine,
    searchForItems,
    canToggleShowMore,
    isShowingMore,
    toggleShowMore,
  } = useRefinementList(props);

  return (
    <>
      <input
        type="search"
        autoComplete="off"
        autoCorrect="off"
        autoCapitalize="off"
        spellCheck={false}
        maxLength={512}
        onChange={(event) => searchForItems(event.currentTarget.value)}
      />
      <ul>
        {items.map((item) => (
          <li key={item.label}>
            <label>
              <input
                type="checkbox"
                checked={item.isRefined}
                onChange={() => refine(item.value)}
              />
              <span>{item.label}</span>
              <span>({item.count})</span>
            </label>
          </li>
        ))}
      </ul>
      <button onClick={toggleShowMore} disabled={!canToggleShowMore}>
        {isShowingMore ? 'Show less' : 'Show more'}
      </button>
    </>
  );
}
Did you find this page helpful?