> ## Documentation Index
> Fetch the complete documentation index at: https://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.

export const Records = () => <Tooltip tip="A record is a searchable object in an Algolia index. Each record consists of named attributes." cta="Algolia records" href="/doc/guides/sending-and-managing-data/prepare-your-data#algolia-records">
    records
  </Tooltip>;

```ts Signature theme={"system"}
refinementList({
  container: string | HTMLElement,
  attribute: string,
  // Optional parameters
  operator?: string,
  limit?: number,
  showMore?: boolean,
  showMoreLimit?: number,
  showMoreButtonLabel?: string,
  searchable?: boolean,
  searchablePlaceholder?: string,
  searchableIsAlwaysActive?: boolean,
  searchableEscapeFacetValues?: boolean,
  sortBy?: string[] | function,
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});
```

## Import

<CodeGroup>
  ```js Package manager theme={"system"}
  import { refinementList } from "instantsearch.js/es/widgets";
  ```

  ```js CDN theme={"system"}
  const { refinementList } = instantsearch.widgets;
  // or directly use instantsearch.widgets.refinementList()
  ```
</CodeGroup>

<Card title="See this widget in action" icon="monitor-play" href="https://instantsearchjs.netlify.app/stories/js/?path=/story/refinements-refinementlist--default" horizontal>
  Preview this widget and its behavior.
</Card>

## About this widget

The `refinementList` widget is one of the most common widgets in a search UI.
With this widget, users can filter the dataset based on facets.

The widget only displays the most relevant facet values for the current search context.
The sort option only affects the facets that are returned by the engine, 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](/doc/guides/managing-results/refine-results/faceting#search-for-facet-values).
This helps you find uncommon facet values.

### Requirements

The [`attribute`](#param-attribute) provided to the widget must be in attributes for faceting,
either on the [dashboard](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard) or using the [`attributesForFaceting`](/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](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard) or using the `searchable` modifier of [`attributesForFaceting`](/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`](/doc/api-reference/widgets/configure/js) widget.
It doesn't change how many items are shown: the limits you set with [`limit`](/doc/api-reference/widgets/refinement-list/js#param-limit)
and [`showMoreLimit`](/doc/api-reference/widgets/refinement-list/js#param-show-more-limit) still apply.

```js JavaScript icon=code theme={"system"}
search.addWidgets([
  // ...
  configure({
    maxValuesPerFacet: 1000,
  }),
]);
```

## Examples

```js JavaScript icon=code theme={"system"}
refinementList({
  container: "#refinement-list",
  attribute: "brand",
});
```

## Options

<ParamField body="container" type="string | HTMLElement" required>
  The CSS Selector of the DOM element inside which the widget is inserted.

  <CodeGroup>
    ```js string theme={"system"}
    refinementList({
      // ...
      container: "#refinement-list",
    });
    ```

    ```js HTMLElement theme={"system"}
    refinementList({
      // ...
      container: document.querySelector("#refinement-list"),
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="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.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    attribute: "categories",
  });
  ```
</ParamField>

<ParamField body="operator" type="string" default="or">
  How to apply refinements.

  * `"or"`: apply an `OR` between all selected values.
  * `"and"`: apply an `AND` between all selected values.

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

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    operator: "and",
  });
  ```
</ParamField>

<ParamField body="limit" type="number" default={10}>
  How many facet values to retrieve.
  When you enable the [`showMore`](#param-show-more) feature,
  this is the number of facet values to display before clicking the "Show more" button.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    //...
    limit: 5,
  });
  ```
</ParamField>

<ParamField body="showMore" type="boolean" default={false}>
  Whether to display a button that expands the number of items.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    showMore: true,
  });
  ```
</ParamField>

<ParamField body="showMoreLimit" type="number">
  The maximum number of displayed items (only used when [`showMore`](#param-show-more) is set to `true`).

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    //...
    showMoreLimit: 20,
  });
  ```
</ParamField>

<ParamField body="showMoreButtonLabel" type="string">
  The static accessible name (`aria-label`) for the **Show more** and **Show less** toggle buttons.
  This option 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.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    //...
    showMoreButtonLabel: "Show more or show less brands",
  });
  ```
</ParamField>

<ParamField body="searchable" type="boolean" default={false}>
  Whether to add a search input to let users search for more facet values.

  To make this feature work,
  you need to make the attribute searchable using the [dashboard](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard) or using the `searchable` modifier of [`attributesForFaceting`](/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.
  </Note>

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    searchable: true,
  });
  ```
</ParamField>

<ParamField body="searchablePlaceholder" type="string" default="Search...">
  The value of the search input's placeholder.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    searchablePlaceholder: "Search our products",
  });
  ```
</ParamField>

<ParamField body="searchableIsAlwaysActive" type="boolean" default={true}>
  When `false`, disables the search input if there are fewer items to display than the [`limit`](#param-limit) option.
  Otherwise, the search input is always usable.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    searchableIsAlwaysActive: false,
  });
  ```
</ParamField>

<ParamField body="searchableEscapeFacetValues" type="boolean" default={true}>
  When `true`, escapes the facet values that are returned from Algolia.
  In this case, the surrounding tags are always `mark`.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    searchableEscapeFacetValues: false,
  });
  ```
</ParamField>

<ParamField body="sortBy" type="string[] | function" default="Uses facetOrdering if set, ['isRefined','count:desc','name:asc']">
  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"`

  It's also possible to give a function,
  which receives items two by two,
  like JavaScript's [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).

  If `facetOrdering` is set for this facet in `renderingContent`,
  and no value for `sortBy` is passed to this widget, `facetOrdering` is used, and the default order as a fallback.

  <Note>
    In some situations, refined facet values might not be present in the data
    returned by Algolia.
  </Note>

  <CodeGroup>
    ```js string[] theme={"system"}
    refinementList({
      // ...
      sortBy: ['count:desc', 'name:asc'],
    });
    ```

    ```js function theme={"system"}
    refinementList({
      // ...
      sortBy(a, b) {
        return a.name < b.name ? 1 : -1;
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="templates" type="object">
  The [templates](#templates) to use for the widget.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    templates: {
      // ...
    },
  });
  ```
</ParamField>

<ParamField body="cssClasses" type="object">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#style-your-widgets):

  * `root`. The root element of the widget.
  * `noRefinementRoot`. The root element if there are no refinements.
  * `noResults`. The root element if there are no results.
  * `list`. The list of results.
  * `item`. The list items. They contain the link and separator.
  * `selectedItem`. Each selected item in the list.
  * `label`. Each label element (when using the default template).
  * `checkbox`. Each checkbox element (when using the default template).
  * `labelText`. Each label text element.
  * `showMore`. The "Show more" element.
  * `disabledShowMore`. The disabled "Show more" element.
  * `count`. Each count element (when using the default template).
  * `searchableRoot`. The root element of the search box.
  * `searchableForm`. The form element of the search box.
  * `searchableInput`. The input element of the search box.
  * `searchableSubmit`. The reset button element of the search box.
  * `searchableSubmitIcon`. The reset button icon of the search box.
  * `searchableReset`. The loading indicator element of the search box.
  * `searchableResetIcon`. The loading indicator icon of the search box.
  * `searchableLoadingIndicator`. The submit button element of the search box.
  * `searchableLoadingIcon`. The submit button icon of the search box.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    cssClasses: {
      root: "MyCustomRefinementList",
      list: [
        "MyCustomRefinementListList",
        "MyCustomRefinementListList--subclass",
      ],
    },
  });
  ```
</ParamField>

<ParamField body="transformItems" type="function">
  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](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  ```js JavaScript icon=code theme={"system"}
  refinementList({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        highlighted: item.highlighted.toUpperCase(),
      }));
    },
  });

  // or, combined with results
  refinementList({
    // ...
    transformItems(items, { results }) {
      return results.page === 0 ? items.slice(0, 5) : items;
    },
  });
  ```
</ParamField>

## Templates

You can customize parts of a widget’s UI using the Templates API.

Each template includes an `html` function,
which you can use as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).
This function safely renders templates as HTML strings and works directly in the browser—no build step required.
For details, see [Templating your UI](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js/#templating-your-ui).

<Note>
  The `html` function is available in InstantSearch.js version 4.46.0 or later.
</Note>

<ParamField body="item" type="string | function">
  The template used for an item. It exposes:

  * `count`. The number of occurrences of the facet in the result set.
  * `isRefined`. Returns `true` if the value is selected.
  * `label`. The label to display.
  * `value`. The value used for refining.
  * `highlighted`. The highlighted label (when using search for facet values). This value is displayed in the default template.
  * `url`. The URL with the selected refinement.
  * `cssClasses`. An object containing all the computed classes for the item.

  <CodeGroup>
    ```js function theme={"system"}
    refinementList({
      // ...
      templates: {
        item(item, { html }) {
          const { url, label, count, isRefined } = item;

          return html`
            <a href="${url}" style="${isRefined ? "font-weight: bold" : ""}">
              <span>${label} (${count})</span>
            </a>
          `;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    refinementList({
      // ...
      templates: {
        item: `
          <a href="{{url}}" style="{{#isRefined}}font-weight: bold{{/isRefined}}">
            <span>{{label}} ({{count}})</span>
          </a>
        `,
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="showMoreText" type="string | function">
  The template for the "Show more" button text. It exposes:

  * `isShowingMore: boolean`. Whether the list is expanded.

  <CodeGroup>
    ```js function theme={"system"}
    refinementList({
      // ...
      templates: {
        showMoreText(data, { html }) {
          return html`<span>${data.isShowingMore ? 'Show less' : 'Show more'}</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    refinementList({
      // ...
      templates: {
        showMoreText: `
          {{#isShowingMore}}
            Show less
          {{/isShowingMore}}
          {{^isShowingMore}}
            Show more
          {{/isShowingMore}}
        `,
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="searchableNoResults" type="string | function">
  The template used for when there are no results.

  <CodeGroup>
    ```js function theme={"system"}
    refinementList({
      // ...
      templates: {
        searchableNoResults(data, { html }) {
          return html`<span>No results</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    refinementList({
      // ...
      templates: {
        searchableNoResults: "No results",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="searchableSubmit" type="string | function">
  The template used for displaying the submit button.

  <CodeGroup>
    ```js function theme={"system"}
    refinementList({
      // ...
      templates: {
        searchableSubmit(data, { html }) {
          return html`<span>submit</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    refinementList({
      // ...
      templates: {
        searchableSubmit: "submit",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="searchableReset" type="string | function">
  The template used for displaying the reset button.

  <CodeGroup>
    ```js function theme={"system"}
    refinementList({
      // ...
      templates: {
        searchableReset(data, { html }) {
          return html`<span>reset</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    refinementList({
      // ...
      templates: {
        searchableReset: "reset",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="searchableLoadingIndicator" type="string | function">
  The template used for displaying the loading indicator.

  <CodeGroup>
    ```js function theme={"system"}
    refinementList({
      // ...
      templates: {
        searchableLoadingIndicator(data, { html }) {
          return html`<span>loading</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    refinementList({
      // ...
      templates: {
        searchableLoadingIndicator: "loading",
      },
    });
    ```
  </CodeGroup>
</ParamField>

## Customize the UI with `connectRefinementList`

If you want to create your own UI of the `refinementList` widget, you can use connectors.

To use `connectRefinementList`, you can import it with the declaration relevant to how you installed InstantSearch.js.

<CodeGroup>
  ```js Package manager theme={"system"}
  import { connectRefinementList } from 'instantsearch.js/es/connectors';
  ```

  ```js CDN theme={"system"}
  const { connectRefinementList } = instantsearch.connectors;
  // or directly use instantsearch.connectors.connectRefinementList()
  ```
</CodeGroup>

Then it's a 3-step process:

```js JavaScript icon=code theme={"system"}
// 1. Create a render function
const renderRefinementList = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customRefinementList = connectRefinementList(
  renderRefinementList
);

// 3. Instantiate
search.addWidgets([
  customRefinementList({
    // instance params
  })
]);
```

[See code examples](#full-example)

### Create a render function

This rendering function is called before the first search (`init` lifecycle step)
and each time results come back from Algolia (`render` lifecycle step).

```js JavaScript icon=code theme={"system"}
const renderRefinementList = (renderOptions, isFirstRender) => {
  const {
    items,
    canRefine,
    refine,
    sendEvent,
    createURL,
    isFromSearch,
    searchForItems,
    hasExhaustiveItems,
    isShowingMore,
    canToggleShowMore,
    toggleShowMore,
    widgetParams,
  } = renderOptions;

  if (isFirstRender) {
    // Do some initial rendering and bind evenjs
  }

  // Render the widget
};
```

#### Rendering options

<ParamField body="items" type="object[]">
  The list of refinement values returned from the Algolia API.

  Each object has the following properties:

  * `value: string`: the value of the item.
  * `label: string`: the label of the item.
  * `count: number`: the number of results that match the item.
  * `isRefined: boolean`: indicates if the refinement is applied.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items } = renderOptions;

    document.querySelector('#refinement-list').innerHTML = `
      <ul>
        ${items
          .map(
            item => `
              <li>
                <a href="#">
                  ${item.label} (${item.count})
                </a>
              </li>`
          )
          .join('')}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="canRefine" type="boolean" required>
  Indicates if search state can be refined.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, canRefine, refine } = renderOptions;

    const container = document.querySelector("#refinement-list");
    if (!canRefine) {
      container.innerHTML = "";
      return;
    }
  };
  ```
</ParamField>

<ParamField body="refine" type="function">
  A function to toggle a refinement.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, refine } = renderOptions;

    const container = document.querySelector("#refinement-list");

    container.innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                <a
                  href="#"
                  data-value="${item.value}"
                  style="font-weight: ${item.isRefined ? "bold" : ""}"
                >
                  ${item.label} (${item.count})
                </a>
              </li>`,
          )
          .join("")}
      </ul>
    `;

    [...container.querySelectorAll("a")].forEach((element) => {
      element.addEventListener("click", (event) => {
        event.preventDefault();
        refine(event.currentTarget.dataset.value);
      });
    });
  };
  ```
</ParamField>

<ParamField body="sendEvent" type="(eventType, facetValue) => void">
  The function to send `click` events. The `click` event is automatically sent when `refine` is called.
  To learn more, see the [`insights`](/doc/api-reference/widgets/insights/js) middleware.

  * `eventType: 'click'`
  * `facetValue: string`

  ```js JavaScript icon=code theme={"system"}
  // For example,
  sendEvent('click', 'Apple');

  /*
    A payload like the following will be sent to the `insights` middleware.
    {
      eventType: 'click',
      insightsMethod: 'clickedFilters',
      payload: {
        eventName: 'Filter Applied',
        filters: ['brand:"Apple"'],
        index: '<index-name>',
      },
      widgetType: 'ais.refinementList',
    }
  */
  ```
</ParamField>

<ParamField body="createURL" type="function">
  Generates a URL for the corresponding search state.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, createURL } = renderOptions;

    document.querySelector("#refinement-list").innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                <a
                  href="${createURL(item.value)}"
                  style="font-weight: ${item.isRefined ? "bold" : ""}"
                >
                  ${item.label} (${item.count})
                </a>
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="isFromSearch" type="boolean">
  Whether the `items` prop contains facet values from the global search or from the search inside the items.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, isFromSearch, refine, searchForItems } = renderOptions;

    const container = document.querySelector("#refinement-list");

    if (isFirstRender) {
      const ul = document.createElement("ul");
      const input = document.createElement("input");

      input.addEventListener("input", (event) => {
        searchForItems(event.currentTarget.value);
      });

      container.appendChild(input);
      container.appendChild(ul);
    }

    const input = container.querySelector("input");

    if (!isFromSearch && input.value) {
      input.value = "";
    }

    container.querySelector("ul").innerHTML = items
      .map(
        (item) => `
          <li>
            <a
              href="#"
              data-value="${item.value}"
              style="font-weight: ${item.isRefined ? "bold" : ""}"
            >
              ${item.label} (${item.count})
            </a>
          </li>
        `,
      )
      .join("");

    [...container.querySelectorAll("a")].forEach((element) => {
      element.addEventListener("click", (event) => {
        event.preventDefault();
        refine(event.currentTarget.dataset.value);
      });
    });
  };
  ```
</ParamField>

<ParamField body="searchForItems" type="function">
  A function to trigger a search inside item values.

  To make this feature work, you need to make the attribute searchable using the [dashboard](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard) or using the `searchable` modifier of [`attributesForFaceting`](/doc/api-reference/api-parameters/attributesForFaceting) with the API.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, searchForItems } = renderOptions;

    const container = document.querySelector("#refinement-list");

    if (isFirstRender) {
      const ul = document.createElement("ul");
      const input = document.createElement("input");

      input.addEventListener("input", (event) => {
        searchForItems(event.currentTarget.value);
      });

      container.appendChild(input);
      container.appendChild(ul);
    }

    container.querySelector("ul").innerHTML = items
      .map(
        (item) => `
          <li>
            <a href="#">
              ${item.label} (${item.count})
            </a>
          </li>
        `,
      )
      .join("");
  };
  ```
</ParamField>

<ParamField body="hasExhaustiveItems" type="boolean">
  Whether the results are complete.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items } = renderOptions;

    document.querySelector("#refinement-list").innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                ${item.label} (${hasExhaustiveItems ? "~" : ""}${item.count})
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="isShowingMore" type="boolean">
  Returns `true` if the menu is displaying all the menu items.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, isShowingMore, toggleShowMore } = renderOptions;

    const container = document.querySelector("#refinement-list");

    if (isFirstRender) {
      const ul = document.createElement("ul");
      const button = document.createElement("button");
      button.textContent = "Show more";

      button.addEventListener("click", () => {
        toggleShowMore();
      });

      container.appendChild(ul);
      container.appendChild(button);
    }

    container.querySelector("ul").innerHTML = items
      .map(
        (item) => `
          <li>
            <a href="#">
              ${item.label} (${item.count})
            </a>
          </li>
        `,
      )
      .join("");

    container.querySelector("button").textContent = isShowingMore
      ? "Show less"
      : "Show more";
  };
  ```
</ParamField>

<ParamField body="canToggleShowMore" type="boolean">
  Returns `true` if the "Show more" button can be activated (if enough items to display and not already displaying more than [`limit`](/doc/api-reference/widgets/refinement-list/js#param-limit) items).

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, canToggleShowMore, toggleShowMore } = renderOptions;

    const container = document.querySelector("#refinement-list");

    if (isFirstRender) {
      const ul = document.createElement("ul");
      const button = document.createElement("button");
      button.textContent = "Show more";

      button.addEventListener("click", () => {
        toggleShowMore();
      });

      container.appendChild(ul);
      container.appendChild(button);
    }

    container.querySelector("ul").innerHTML = items
      .map(
        (item) => `
          <li>
            <a href="#">
              ${item.label} (${item.count})
            </a>
          </li>
        `,
      )
      .join("");

    container.querySelector("button").disabled = !canToggleShowMore;
  };
  ```
</ParamField>

<ParamField body="toggleShowMore" type="function">
  Toggles the number of displayed values between [`limit`](/doc/api-reference/widgets/refinement-list/js#param-limit) and [`showMoreLimit`](/doc/api-reference/widgets/refinement-list/js#param-show-more-limit).

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { items, toggleShowMore } = renderOptions;

    const container = document.querySelector("#refinement-list");

    if (isFirstRender) {
      const ul = document.createElement("ul");
      const button = document.createElement("button");
      button.textContent = "Show more";

      button.addEventListener("click", () => {
        toggleShowMore();
      });

      container.appendChild(ul);
      container.appendChild(button);
    }

    container.querySelector("ul").innerHTML = items
      .map(
        (item) => `
          <li>
            <a href="#">
              ${item.label} (${item.count})
            </a>
          </li>
        `,
      )
      .join("");
  };
  ```
</ParamField>

<ParamField body="widgetParams" type="object">
  All original widget options forwarded to the render function.

  ```js JavaScript icon=code theme={"system"}
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const { widgetParams } = renderOptions;

    widgetParams.container.innerHTML = "...";
  };

  // ...

  search.addWidgets([
    customRefinementList({
      // ...
      container: document.querySelector("#refinement-list"),
    }),
  ]);
  ```
</ParamField>

### Create and instantiate the custom widget

First, create your custom widgets using a rendering function.
Then, instantiate them with parameters.

There are two kinds of parameters you can pass:

* **Instance parameters**. Predefined options that configure Algolia's behavior.
* **Custom parameters**. Parameters you define to make the widget reusable and adaptable.

Inside the `renderFunction`, both instance and custom parameters are accessible through `connector.widgetParams`.

```js JavaScript icon=code theme={"system"}
const customRefinementList = connectRefinementList(
  renderRefinementList
);

search.addWidgets([
  customRefinementList({
    attribute: string,
    // Optional parameters
    operator: string,
    limit: number,
    showMoreLimit: number,
    escapeFacetValues: boolean,
    sortBy: string[]|function,
    transformItems: function,
  })
]);
```

#### Instance options

<ParamField body="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.

  ```js JavaScript icon=code theme={"system"}
  customRefinementList({
    attribute: "brand",
  });
  ```
</ParamField>

<ParamField body="operator" type="string ('or'|'and')" default="or">
  How to apply refinements.

  * `"or"`: apply an `OR` between all selected values.
  * `"and"`: apply an `AND` between all selected values.

  ```js JavaScript icon=code theme={"system"}
  customRefinementList({
    // ...
    operator: "and",
  });
  ```
</ParamField>

<ParamField body="limit" type="number" default={10}>
  How many facet values to retrieve.
  When [isShowingMore](/doc/api-reference/widgets/refinement-list/js#param-is-showing-more) is `false`,
  this is the number of facet values displayed before clicking the "Show more" button.

  ```js JavaScript icon=code theme={"system"}
  customRefinementList({
    // ...
    limit: 5,
  });
  ```
</ParamField>

<ParamField body="showMoreLimit" type="number">
  The maximum number of items to display if the widget is showing more items.
  Needs to be bigger than the [`limit`](/doc/api-reference/widgets/refinement-list/js#param-limit) parameter.

  ```js JavaScript icon=code theme={"system"}
  customRefinementList({
    // ...
    showMoreLimit: 20,
  });
  ```
</ParamField>

<ParamField body="escapeFacetValues" type="boolean" default={true}>
  When activate, escapes the facet values that are returned from Algolia.
  In this case, the surrounding tags are always [`mark`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark).

  ```js JavaScript icon=code theme={"system"}
  customRefinementList({
    // ...
    escapeFacetValues: false,
  });
  ```
</ParamField>

<ParamField body="sortBy" type="string[] | function" default="Uses facetOrdering if set, ['isRefined','count:desc','name:asc']">
  How to sort refinements. Must be one or more of the following strings:

  * `"count:asc"`
  * `"count:desc"`
  * `"name:asc"`
  * `"name:desc"`
  * `"isRefined"`

  It's also possible to give a function,
  which receives items two by two, like JavaScript's [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).

  If `facetOrdering` is set for this facet in `renderingContent`,
  and no value for `sortBy` is passed to this widget, `facetOrdering` is used, and the default order as a fallback.

  <Note>
    In some situations, refined facet values might not be present in the data
    returned by Algolia.
  </Note>

  <CodeGroup>
    ```js string[] theme={"system"}
    customRefinementList({
      // ...
      sortBy: ['count:desc', 'name:asc'],
    });
    ```

    ```js function theme={"system"}
    customRefinementList({
      // ...
      sortBy(a, b) {
        return a.name < b.name ? 1 : -1;
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="transformItems" type="function">
  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](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  ```js JavaScript icon=code theme={"system"}
  customRefinementList({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        label: item.label.toUpperCase(),
      }));
    },
  });

  // or, combined with results
  customRefinementList({
    // ...
    transformItems(items, { results }) {
      return results.page === 0 ? items.slice(0, 5) : items;
    },
  });
  ```
</ParamField>

### Full example

<CodeGroup>
  ```html HTML theme={"system"}
  <div id="refinement-list"></div>
  ```

  ```js JavaScript theme={"system"}
  // 1. Create a render function
  const renderRefinementList = (renderOptions, isFirstRender) => {
    const {
      items,
      isFromSearch,
      refine,
      createURL,
      isShowingMore,
      canToggleShowMore,
      searchForItems,
      toggleShowMore,
      widgetParams,
    } = renderOptions;

    if (isFirstRender) {
      const input = document.createElement("input");
      const ul = document.createElement("ul");
      const button = document.createElement("button");
      button.textContent = "Show more";

      input.addEventListener("input", (event) => {
        searchForItems(event.currentTarget.value);
      });

      button.addEventListener("click", () => {
        toggleShowMore();
      });

      widgetParams.container.appendChild(input);
      widgetParams.container.appendChild(ul);
      widgetParams.container.appendChild(button);
    }

    const input = widgetParams.container.querySelector("input");

    if (!isFromSearch && input.value) {
      input.value = "";
    }

    widgetParams.container.querySelector("ul").innerHTML = items
      .map(
        (item) => `
          <li>
            <a
              href="${createURL(item.value)}"
              data-value="${item.value}"
              style="font-weight: ${item.isRefined ? "bold" : ""}"
            >
              ${item.label} (${item.count})
            </a>
          </li>
        `,
      )
      .join("");

    [...widgetParams.container.querySelectorAll("a")].forEach((element) => {
      element.addEventListener("click", (event) => {
        event.preventDefault();
        refine(event.currentTarget.dataset.value);
      });
    });

    const button = widgetParams.container.querySelector("button");

    button.disabled = !canToggleShowMore;
    button.textContent = isShowingMore ? "Show less" : "Show more";
  };

  // 2. Create the custom widget
  const customRefinementList = connectRefinementList(renderRefinementList);

  // 3. Instantiate
  search.addWidgets([
    customRefinementList({
      container: document.querySelector("#refinement-list"),
      attribute: "brand",
      showMoreLimit: 20,
    }),
  ]);
  ```
</CodeGroup>
