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

# numericMenu

> Shows a list of numeric filters for refining search results.

export const Index = () => <Tooltip tip="An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.">
    index
  </Tooltip>;

<div className="not-prose algolia-flavor-switcher">
  <div className="afs-dropdown">
    <div className="afs-trigger" role="button" tabIndex="0" aria-haspopup="listbox">
      <span className="afs-current">JavaScript</span>

      <svg className="afs-chevron lucide lucide-chevron-down" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>

    <ul className="afs-menu" role="listbox">
      <li role="option" aria-selected="true"><a className="afs-option is-current" href="/doc/api-reference/widgets/numeric-menu/js"><span className="afs-option-name">JavaScript</span><span className="afs-option-lib">InstantSearch.js</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/numeric-menu/react"><span className="afs-option-name">React</span><span className="afs-option-lib">React InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/numeric-menu/vue"><span className="afs-option-name">Vue</span><span className="afs-option-lib">Vue InstantSearch</span></a></li>
    </ul>
  </div>
</div>

```ts Signature theme={"system"}
numericMenu({
  container: string | HTMLElement,
  attribute: string,
  items: object[],
  // Optional parameters
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});
```

## Import

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

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

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

## About this widget

The `numericMenu` widget displays a list of numeric filters in a list.
Those numeric filters are pre-configured when creating the widget.

### Requirements

The value provided to the `attribute` option must be an attribute which is a number in the <Index />, not a string.

## Examples

```js JavaScript icon=code theme={"system"}
numericMenu({
  container: "#numeric-menu",
  attribute: "price",
  items: [
    { label: "All" },
    { label: "Less than 500$", end: 500 },
    { label: "Between 500$ - 1000$", start: 500, end: 1000 },
    { label: "More than 1000$", start: 1000 },
  ],
});
```

## Options

<ParamField body="container" type="string | HTMLElement" required>
  The CSS Selector or `HTMLElement` to insert the widget into.

  <CodeGroup>
    ```js string theme={"system"}
    numericMenu({
      // ...
      container: "#numeric-menu",
    });
    ```

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

<ParamField body="attribute" type="string" required>
  The name of the attribute in the record.

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

<ParamField body="items" type="object[]" required>
  A list of all the options to display, with:

  * `label: string`. Label of the option.
  * `start: number`. The option must be greater than or equal to `start` (lower bound).
  * `end: number`. The option must be smaller than or equal to `end` (upper bound).

  ```js JavaScript icon=code theme={"system"}
  numericMenu({
    // ...
    items: [
      { label: "All" },
      { label: "Less than 500$", end: 500 },
      { label: "Between 500$ - 1000$", start: 500, end: 1000 },
      { label: "More than 1000$", start: 1000 },
    ],
  });
  ```
</ParamField>

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

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

<ParamField body="cssClasses" type="object" default="{}">
  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`. Container class without results.
  * `list`. The list of results.
  * `item`. The list items.
  * `selectedItem`. The selected item in the list.
  * `label`. The label of each item.
  * `labelText`. The text element of each item.
  * `radio`. The radio button of each item.

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

<ParamField body="transformItems" type="function" default="items => items">
  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"}
  numericMenu({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        label: item.label.toUpperCase(),
      }));
    },
  });

  // or: combined with results
  numericMenu({
    // ...
    transformItems(items, { results }) {
      return items.map((item) => ({
        ...item,
        label:
          item.isRefined && results
            ? `${item.label} (${results.nbHits} hits)`
            : item.label,
      }));
    },
  });
  ```
</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 for each item. It exposes:

  * `attribute: string`. The name of the attribute.
  * `label: string`. The label for the option.
  * `value: string`. The encoded URL of the bounds object with a `{start, end}` form. This value can be used verbatim in the webpage and can be read by `refine` directly. If you want to inspect the value, you can do `JSON.parse(window.decodeURI(value))` to get the object.
  * `isRefined: boolean`. Whether the refinement is selected.
  * `url: string`. The URL with the applied refinement.
  * `cssClasses: object`. The CSS classes provided to the widget.

  <CodeGroup>
    ```js function theme={"system"}
    numericMenu({
      // ...
      templates: {
        item(data, { html }) {
          return html` <label class="${data.cssClasses.label}">
            <input
              type="radio"
              class="${data.cssClasses.radio}"
              name="${data.attribute}"
              ${data.isRefined ? " checked" : ""}
            />
            <span class="${data.cssClasses.labelText}"> ${data.label} </span>
          </label>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    numericMenu({
      // ...
      templates: {
        item: `
          <label class="{{cssClasses.label}}">
            <input
              type="radio"
              class="{{cssClasses.radio}}"
              name="{{attribute}}"
              {{#isRefined}} checked{{/isRefined}}
            />
            <span class="{{cssClasses.labelText}}">
              {{label}}
            </span>
          </label>`,
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-NumericMenu">
  <ul class="ais-NumericMenu-list">
    <li class="ais-NumericMenu-item ais-NumericMenu-item--selected">
      <label class="ais-NumericMenu-label">
        <input
          class="ais-NumericMenu-radio"
          type="radio"
          name="NumericMenu"
          checked
        />
        <span class="ais-NumericMenu-labelText">All</span>
      </label>
    </li>
    <li class="ais-NumericMenu-item">
      <label class="ais-NumericMenu-label">
        <input class="ais-NumericMenu-radio" type="radio" name="NumericMenu" />
        <span class="ais-NumericMenu-labelText">Less than 500</span>
      </label>
    </li>
  </ul>
</div>
```

## Customize the UI with `connectNumericMenu`

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

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

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

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

Then it's a 3-step process:

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

// 2. Create the custom widget
const customNumericMenu = connectNumericMenu(renderNumericMenu);

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

### 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 renderNumericMenu = (renderOptions, isFirstRender) => {
  const { items, canRefine, refine, sendEvent, createURL, widgetParams } =
    renderOptions;

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

  // Render the widget
};
```

#### Rendering options

<ParamField body="items" type="object[]">
  The list of available options, with each option:

  * `label: string`. The label for the option.
  * `value: string`. The encoded URL of the bounds object with the `{start, end}` form. This value can be used verbatim in the webpage and can be read by `refine` directly. If you want to inspect the value, you can do `JSON.parse(window.decodeURI(value))` to get the object.
  * `isRefined: boolean`. Whether the refinement is selected.

  ```js JavaScript icon=code theme={"system"}
  numericMenu({
    // ...
    templates: {
      item(data, { html }) {
        return html` <label class="${data.cssClasses.label}">
          <input
            type="radio"
            class="${data.cssClasses.radio}"
            name="${data.attribute}"
            ${data.isRefined ? " checked" : ""}
          />
          <span class="${data.cssClasses.labelText}"> ${data.label} </span>
        </label>`;
      },
    },
  });
  ```
</ParamField>

<ParamField body="canRefine" type="boolean" since={['since: v4.45.0']}>
  Whether the search can be refined.
  This is `true` if there are results or if a range other than "All" is selected.

  ```js JavaScript icon=code theme={"system"}
  const renderNumericMenu = (renderOptions, isFirstRender) => {
    // `canRefine` is only available from v4.45.0
    // Use `hasNoResults` in earlier minor versions.
    const { items, canRefine } = renderOptions;

    document.querySelector("#numeric-menu").innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                <label>
                  <input
                    type="radio"
                    name="price"
                    value="${item.value}"
                    ${item.isRefined ? "checked" : ""}
                    ${!canRefine ? "disabled" : ""}
                  />
                  ${item.label}
                </label>
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="refine" type="function">
  Sets the selected value and triggers a new search.

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

    const container = document.querySelector("#numeric-menu");

    container.innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                <label>
                  <input
                    type="radio"
                    name="price"
                    value="${item.value}"
                    ${item.isRefined ? "checked" : ""}
                  />
                  ${item.label}
                </label>
              </li>`,
          )
          .join("")}
      </ul>
    `;

    [...container.querySelectorAll("input")].forEach((element) => {
      element.addEventListener("change", (event) => {
        refine(event.currentTarget.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", [10, 20]);

  /*
    A payload like the following will be sent to the `insights` middleware.
    {
      eventType: 'click',
      insightsMethod: 'clickedFilters',
      payload: {
        eventName: 'Filter Applied',
        filters: ['numerics<=20', 'numerics>=10'],
        index: '',
      },
      widgetType: 'ais.numericMenu',
    }
  */
  ```
</ParamField>

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

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

    document.querySelector("#numeric-menu").innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                <a href="${createURL(item.value)}">${item.label}</a>
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

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

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

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

  // ...

  search.addWidgets([
    customNumericMenu({
      // ...
      container: document.querySelector("#numeric-menu"),
    }),
  ]);
  ```
</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 customNumericMenu = connectNumericMenu(
  renderNumericMenu
);

search.addWidgets([
  customNumericMenu({
    attribute: string,
    items: object[],
    // Optional parameters
    transformItems?: function,
  })
]);
```

#### Instance options

<ParamField body="attribute" type="string" required>
  The name of the attribute in the record.

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

<ParamField body="items" type="object[]" required>
  A list of all the options to display, with:

  * `label: string`. Label of the option.
  * `start: string`. The option must be greater than or equal to `start` (lower bound).
  * `end: string`. The option must be smaller than or equal to `end` (upper bound).

  ```js JavaScript icon=code theme={"system"}
  customNumericMenu({
    // ...
    items: [
      { label: "All" },
      { label: "Less than 500$", end: 500 },
      { label: "Between 500$ - 1000$", start: 500, end: 1000 },
      { label: "More than 1000$", start: 1000 },
    ],
  });
  ```
</ParamField>

<ParamField body="transformItems" type="function" default="items => items">
  <TranformItems />

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

  // or: combined with results
  customNumericMenu({
    // ...
    transformItems(items, { results }) {
      return items.map((item) => ({
        ...item,
        label:
          item.isRefined && results
            ? `${item.label} (${results.nbHits} hits)`
            : item.label,
      }));
    },
  });
  ```
</ParamField>

### Full example

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

  ```js JavaScript theme={"system"}
  // Create the render function
  const renderNumericMenu = (renderOptions, isFirstRender) => {
    // `canRefine` is only available from v4.45.0
    // Use `hasNoResults` in earlier minor versions.
    const { items, canRefine, refine, widgetParams } = renderOptions;

    widgetParams.container.innerHTML = `
      <ul>
        ${items
          .map(
            (item) => `
              <li>
                <label>
                  <input
                    type="radio"
                    name="${widgetParams.attribute}"
                    value="${item.value}"
                    ${item.isRefined ? "checked" : ""}
                    ${!canRefine ? "disabled" : ""}
                  />
                  ${item.label}
                </label>
              </li>`,
          )
          .join("")}
      </ul>
    `;

    [...widgetParams.container.querySelectorAll("input")].forEach((element) => {
      element.addEventListener("change", (event) => {
        refine(event.currentTarget.value);
      });
    });
  };

  // Create the custom widget
  const customNumericMenu = connectNumericMenu(renderNumericMenu);

  // Instantiate the custom widget
  search.addWidgets([
    customNumericMenu({
      container: document.querySelector("#numeric-menu"),
      attribute: "price",
      items: [
        { label: "All" },
        { label: "Less than 500$", end: 500 },
        { label: "Between 500$ - 1000$", start: 500, end: 1000 },
        { label: "More than 1000$", start: 1000 },
      ],
    }),
  ]);
  ```
</CodeGroup>
