> ## Documentation Index
> Fetch the complete documentation index at: https://www.algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# RefinementList

> Shows a list of facets for refining search results.

> [!NOTE]
>
> This is the **React InstantSearch v7** documentation.
> If you're upgrading from v6, see the [upgrade guide](https://www.algolia.com/doc/guides/building-search-ui/upgrade-guides/react.md#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
> If you were using React InstantSearch Hooks,
> this v7 documentation applies—just check for [necessary changes](https://www.algolia.com/doc/guides/building-search-ui/upgrade-guides/react.md#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
> To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).

```tsx Signature theme={"system"}
<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

```jsx JavaScript icon=code theme={"system"}
import { RefinementList } from "react-instantsearch";
```

> [card] [See this widget in action](https://instantsearchjs.netlify.app/examples/js/showcase/?view=reference\&flavor=react\&widget=refinementList)
>
> Preview this widget and its behavior.

## 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`](#param-sort-by) option only affects how the facets are ordered, not which facets are returned.

This widget includes a "search for facet values" feature,
enabling users to search through the [values of a specific facet attribute](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting#search-for-facet-values).
This helps you find uncommon facet values.

> [!NOTE]
>
> The [`attribute`](#param-attribute) provided to the widget must be in attributes for faceting,
> either on the [dashboard](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard.md) or using the [`attributesForFaceting`](https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting) parameter with the API.
>
> If you are using the [`searchable`](#param-searchable) prop, you also need to make the attribute searchable using the [dashboard](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard.md) or using the `searchable` modifier of [`attributesForFaceting`](https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting) with the API.

### Disappearing facet values

With many facet values, the available options can change depending on the user's query.
The refinement widget displays the most common facet values for a given query.

A user's chosen value can vanish if they alter the query.
This occurs because only the most common facet values are displayed when there are many options.
A previously selected value might not appear if it's uncommon for the new query.

To also show less common values, adjust the maximum number of values with the [`configure`](https://www.algolia.com/doc/api-reference/widgets/configure/react) widget.
It doesn't change how many items are shown: the limits you set with [`limit`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/react#param-limit) and [`showMoreLimit`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/react#param-show-more-limit) still apply.

### How to implement a "Show more" feature

A custom `useRefinementList` widget displays up to `showMoreLimit` refinement `items`.
You can sort the items as desired before they're trimmed.
However, you'll need to slice to the appropriate `limit` and keep track of `isShowingMore` in the local state:

```jsx JavaScript icon=code theme={"system"}
const CustomRefinementList = connectRefinementList(function RefinementList({
  items,
  limit,
  showMoreLimit,
}) {
  const [isShowingMore, toggleShowMore] = React.useState(false);
  const itemsToDisplay = items.slice(0, isShowingMore ? showMoreLimit : limit);

  // render using `itemsToDisplay`
});
```

> [!TIP]
>
> You can also create your own UI with [`useRefinementList`](#hook).

## Examples

```jsx JavaScript icon=code theme={"system"}
import React from "react";
import { liteClient as 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

**attribute** `string` *required*

The name of the attribute in the records (A record is a searchable object in an Algolia index. Each record consists of named attributes.).

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

```jsx JavaScript icon=code theme={"system"}
<RefinementList attribute="categories" />;
```

**operator** `'and'|'or'` (default: 'or')

How the facets are combined.

* `'or'`: Returns results matching any of the selected values.
* `'and'`: Returns results matching all selected values.

Use [filters or facet filters](https://www.algolia.com/doc/guides/managing-results/refine-results/filtering/in-depth/filters-and-facetfilters.md) for more complex result refinement.

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  operator="and"
/>;
```

**limit** `number` (default: 10)

How many facet values to retrieve.

When you set [`showMore`](#param-show-more) and [`showMoreLimit`](#param-show-more-limit),
this is the number of facet values to display before clicking the Show more button.

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  limit={5}
/>;
```

**showMore** `boolean` (default: false)

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

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  showMore={true}
/>;
```

**showMoreLimit** `number`

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

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  showMoreLimit={20}
/>;
```

**searchable** `boolean` (default: false)

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

You need to make the `attribute` searchable using the [dashboard](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard.md)) or using the `searchable` modifier of [`attributesForFaceting`](https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting) with the API.

> [!NOTE]
>
> In some situations, refined facet values might not be present in the data
> returned by Algolia.

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  searchable={true}
/>;
```

**searchablePlaceholder** `string`

The value of the search input's placeholder.

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  searchablePlaceholder="Search our products"
/>;
```

**sortBy** `string[] | (a: FacetValue, b: FacetValue) =\> number` (default: \['isRefined', 'count:desc', 'name:asc'], or `facetOrdering` if set)

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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).

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.

> [!NOTE]
>
> In some situations, refined facet values might not be present in the data
> returned by Algolia.

```jsx String theme={"system"}
<RefinementList
  // ...
  sortBy={["count:desc", "name:asc"]}
/>;
```

```jsx Function theme={"system"}
const sortByName = (a, b) => {
  return a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1;
};

function Search() {
  return (
    <RefinementList
      // ...
      sortBy={sortByName}
    />
  );
}
```

```tsx Function (TypeScript) theme={"system"}
import type { RefinementListProps } from "react-instantsearch";

const sortByName: RefinementListProps["sortBy"] = (a, b) => {
  return a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1;
};

function Search() {
  return (
    <RefinementList
      // ...
      sortBy={sortByName}
    />
  );
}
```

**escapeFacetValues** `boolean` (default: true)

Escapes the content of the facet values returned by Algolia.

When using this parameter,
the highlighting tags are always [`mark`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark).

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  escapeFacetValues={false}
/>;
```

**transformItems** `(items: object[], metadata: \{ results: SearchResults \}) =\> object[]`

A function that receives the list of items before they are displayed.
It should return a new array with the same structure.
Use this to transform, filter, or reorder the items.

The function also has access to the full `results` data,
including all standard [response parameters](https://www.algolia.com/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/js.md)
and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
such as `disjunctiveFacetsRefinements`.

```jsx JavaScript theme={"system"}
const transformItems = (items) => {
  return items.map((item) => ({
    ...item,
    label: item.label.toUpperCase(),
  }));
};

function Search() {
  return (
    <RefinementList
      // ...
      transformItems={transformItems}
    />
  );
}
```

```tsx TypeScript theme={"system"}
import type { RefinementListProps } from 'react-instantsearch';

const transformItems: RefinementListProps['transformItems'] = (items) => {
  return items.map((item) => ({
    ...item,
    label: item.label.toUpperCase(),
  }));
};

function Search() {
  return (
    <RefinementList
      // ...
      transformItems={transformItems}
    />
  );
}
```

**classNames** `Partial\<RefinementListClassNames\>`

The [CSS classes you can override](https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react.md#style-your-widgets)
and pass to the widget's elements.
It's useful to style widgets with class-based CSS frameworks like [Bootstrap](https://getbootstrap.com)
or [Tailwind CSS](https://tailwindcss.com).

* `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 "Show more" button when it's unavailable.

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  classNames={{
    root: "MyCustomRefinementList",
    searchBox:
      "MyCustomRefinementListSearchBox MyCustomRefinementListSearchBox--subclass",
  }}
/>;
```

**translations** `Partial\<RefinementListTranslations\>`

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 doesn't return any results.
* `showMoreButtonText`. The text for the "Show more" button.
* `showMoreButtonLabel`. The static accessible name (`aria-label`) for the **Show more** and **Show less** toggle buttons.
  This translation is only used when [`showMore`](#param-show-more) is `true`.
  Use a label that works for both expanded and collapsed states because this value doesn't change as the button expands or collapses.

```jsx JavaScript icon=code theme={"system"}
<RefinementList
  // ...
  searchable
  showMore
  translations={{
    submitButtonTitle: "Submit",
    resetButtonTitle: "Reset",
    noResultsText: "No brands matching your query.",
    showMoreButtonText({ isShowingMore }) {
      return isShowingMore ? "Show less brands" : "Show more brands";
    },
    showMoreButtonLabel: "Show more or show less brands",
  }}
/>;
```

**...props** `React.ComponentProps\<'div'\>`

Any `div` prop to forward to the root element of the widget.

```jsx JavaScript icon=code theme={"system"}
<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](#parameters) and returns [APIs](#hook).
It must be used inside the [`InstantSearch`](https://www.algolia.com/doc/api-reference/widgets/instantsearch/react) component.

### Usage

First, create your React component:

```jsx JavaScript icon=code theme={"system"}
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:

```jsx JavaScript icon=code theme={"system"}
<CustomRefinementList {...props} />;
```

### Parameters

Hooks accept parameters. You can either pass them manually or forward props from a custom component.

> [!NOTE]
>
> When passing functions to Hooks, ensure stable references to prevent unnecessary re-renders.
> Use [`useCallback()`](https://reactjs.org/docs/hooks-reference.html#usecallback) to keep function references stable.
> You don't need to do this for arrays and objects.

**attribute** `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.

```jsx JavaScript icon=code theme={"system"}
const refinementListApi = useRefinementList({
  attribute: "categories",
});
```

**operator** `'and'|'or'` (default: or)

How the [filters](https://www.algolia.com/doc/api-reference/api-parameters/filters.md) are combined.

* `'or'`: Returns results matching any of the selected values.
* `'and'`: Returns results matching all selected values.

```jsx JavaScript icon=code theme={"system"}
const refinementListApi = useRefinementList({
  // ...
  operator: "and",
});
```

**limit** `number` (default: 10)

How many facet values to retrieve.

When you set [`showMore`](#param-show-more) and [`showMoreLimit`](#param-show-more-limit),
this is the number of facet values to display before clicking the Show more button.

```jsx JavaScript icon=code theme={"system"}
const refinementListApi = useRefinementList({
  // ...
  limit: 5,
});
```

**showMore** `boolean` (default: false)

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

```jsx JavaScript icon=code theme={"system"}
const refinementListApi = useRefinementList({
  // ...
  showMore: true,
});
```

**showMoreLimit** `number`

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

```jsx JavaScript icon=code theme={"system"}
const refinementListApi = useRefinementList({
  // ...
  showMoreLimit: 20,
});
```

**sortBy** `string[] | (a: FacetValue, b: FacetValue) =\> number` (default: \['isRefined', 'count:desc', 'name:asc'], or `facetOrdering` if set)

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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).

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.

> [!NOTE]
>
> In some situations, refined facet values might not be present in the data
> returned by Algolia.

```jsx String theme={"system"}
const refinementListApi = useRefinementList({
  // ...
  sortBy: ["count:desc", "name:asc"],
});
```

```jsx Function theme={"system"}
const sortByName = (a, b) => {
  return a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1;
};

function RefinementList() {
  const refinementListApi = useRefinementList({
    // ...
    sortBy,
  });

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

```tsx Function (TypeScript) theme={"system"}
import type { UseRefinementListProps } from "react-instantsearch";

const sortByName: UseRefinementListProps["sortBy"] = (a, b) => {
  return a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1;
};

function RefinementList() {
  const refinementListApi = useRefinementList({
    // ...
    sortBy,
  });

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

**escapeFacetValues** `boolean` (default: true)

Escapes the content of the facet values returned by Algolia.

When using this parameter, the highlighting tags are always [`mark`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark).

```jsx JavaScript icon=code theme={"system"}
const refinementListApi = useRefinementList({
  // ...
  escapeFacetValues: false,
});
```

**transformItems** `(items: object[], metadata: \{ results: SearchResults \}) =\> object[]`

A function that receives the list of items before they are displayed.
It should return a new array with the same structure.
Use this to transform, filter, or reorder the items.

The function also has access to the full `results` data,
including all standard [response parameters](https://www.algolia.com/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/js.md)
and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
such as `disjunctiveFacetsRefinements`.

```jsx JavaScript theme={"system"}
const transformItems = (items) => {
  return items.map((item) => ({
    ...item,
    label: item.label.toUpperCase(),
  }));
};

function RefinementList() {
  const refinementListApi = useRefinementList({
    // ...
    transformItems,
  });

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

```tsx TypeScript theme={"system"}
import type { UseRefinementListProps } from 'react-instantsearch';

const transformItems: UseRefinementListProps['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.

**items** `RefinementListItem[]`

The list of filtering values returned by Algolia.

```ts Type definition theme={"system"}
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** `boolean`

Whether the results are exhaustive.

**createURL** `(value: string) =\> string`

Creates the next state URL of a selected refinement.

**refine** `(value: string) =\> string`

Applies the selected refinement.

**sendEvent** `(eventType: string, facetValue: string, eventName?: string) =\> void`

Sends an event to the Insights middleware.

**searchForItems** `(query: string) =\> void`

Searches for values in the list.

**isFromSearch** `boolean`

Whether the values are from an index (An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.) search.

**canRefine** `boolean`

Whether a refinement can be applied.

**canToggleShowMore** `boolean`

Whether the Show more button can be activated, meaning there are enough
additional items to display, or already displaying over the
[`limit`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/react#param-limit) items.

**isShowingMore** `boolean`

Whether the menu is displaying all the menu items.

**toggleShowMore** `() =\> void`

Toggles the number of values displayed between [`limit`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/react#param-limit)
and [`showMoreLimit`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/react#param-show-more-limit).

### Example

```jsx JavaScript theme={"system"}
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>
    </>
  );
}
```

```tsx TypeScript theme={"system"}
import React from "react";
import { useRefinementList, UseRefinementListProps } from "react-instantsearch";

function CustomRefinementList(props: UseRefinementListProps) {
  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>
    </>
  );
}
```
