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

# Menu

> Shows a menu for refining search results based on a selected facet value.

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>;

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#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](/doc/guides/building-search-ui/upgrade-guides/react/#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/).
</Note>

```tsx Signature theme={"system"}
<Menu
  attribute={string}
  // Optional parameters
  limit={number}
  showMore={boolean}
  showMoreLimit={number}
  sortBy={string[] | function}
  transformItems={function}
  classNames={object}
  translations={object}
  ...props={ComponentProps<'div'>}
/>
```

## Import

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

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

## About this widget

`<Menu>` is a widget that displays a list of facets and lets users choose a single value.

<Note>
  The `<Menu>` widget uses a hierarchical refinement internally, so it can't refine values that include the default separator (`>`).
  To support these values, use the [`<HierarchicalMenu>`](/doc/api-reference/widgets/hierarchical-menu/react) widget instead.
</Note>

### Requirements

Ensure that the attribute provided to the hook is already declared as an [attribute for faceting](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting).

<Tip>You can also create your own UI with [`useMenu`](#hook).</Tip>

## Examples

```jsx JavaScript icon=code theme={"system"}
import React from "react";
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { InstantSearch, Menu } from "react-instantsearch";

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

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <Menu attribute="categories" />
    </InstantSearch>
  );
}
```

## Props

<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.

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

<ParamField body="limit" type="number" default={10}>
  How many facet values to retrieve.

  [`showMore`](#param-show-more) and [`showMoreLimit`](#param-show-more-limit) determine the number of facet values to display before clicking the Show more button.

  ```jsx JavaScript icon=code theme={"system"}
  <Menu
    // ...
    limit={15}
  />;
  ```
</ParamField>

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

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

<ParamField body="showMoreLimit" type="number">
  The maximum number of items to display if the widget is showing more than the [`limit`](#param-limit) items.

  ```jsx JavaScript icon=code theme={"system"}
  <Menu
    // ...
    showMoreLimit={25}
  />;
  ```
</ParamField>

<ParamField body="sortBy" type="string[] | (a: FacetValue, b: FacetValue) => number" default="['isRefined', '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).

  If you leave the default setting for 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.

  <CodeGroup>
    ```jsx String theme={"system"}
    <Menu
      // ...
      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 (
        <Menu
          // ...
          sortBy={sortByName}
        />
      );
    }
    ```

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

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

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

<ParamField body="transformItems" type="(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](/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`.

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

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

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

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

    function Search() {
      return (
        <Menu
          // ...
          transformItems={transformItems}
        />
      );
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="classNames" type="Partial<MenuClassNames>">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react#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.
  * `list`. The list element.
  * `item`. Each item element..
  * `selectedItem`. The selected item element.
  * `link`. The link of each item.
  * `label`. The label of each item.
  * `count`. The count of each item.
  * `showMore`. The "Show more" button.
  * `disabledShowMore`. The disabled "Show more" button.

  ```jsx JavaScript icon=code theme={"system"}
  <Menu
    // ...
    classNames={{
      root: "MyCustomMenu",
      list: "MyCustomMenuList MyCustomMenuList--subclass",
    }}
  />;
  ```
</ParamField>

<ParamField body="translations" type="Partial<MenuTranslations>">
  A mapping of keys to translation values.

  * `showMoreButtonText`. The text for the "Show more" button.

  ```jsx JavaScript icon=code theme={"system"}
  <Menu
    // ...
    showMore
    translations={{
      showMoreButtonText({ isShowingMore }) {
        return isShowingMore ? "Show less brands" : "Show more brands";
      },
    }}
  />;
  ```
</ParamField>

<ParamField body="...props" type="React.ComponentProps<'div'>">
  Any `<div>` prop to forward to the root element of the widget.

  ```jsx JavaScript icon=code theme={"system"}
  <Menu
    // ...
    className="MyCustomMenu"
    title="My custom title"
  />;
  ```
</ParamField>

## Hook

React InstantSearch let you create your own UI for the `<Menu>` widget with `useMenu`.
Hooks provide APIs to access the widget state and interact with InstantSearch.

The `useMenu` Hook accepts [parameters](#parameters) and returns [APIs](#hook).
It must be used inside the [`<InstantSearch>`](/doc/api-reference/widgets/instantsearch/react) component.

### Usage

First, create your React component:

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

function CustomMenu(props) {
  const {
    items,
    createURL,
    refine,
    canRefine,
    isShowingMore,
    toggleShowMore,
    canToggleShowMore,
    sendEvent,
  } = useMenu(props);

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

Then, render the widget:

```jsx JavaScript icon=code theme={"system"}
<CustomMenu {...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) for memoization.
  Arrays and objects are automatically memoized.
</Note>

<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.

  ```jsx JavaScript icon=code theme={"system"}
  const menuApi = useMenu({
    attribute: "categories",
  });
  ```
</ParamField>

<ParamField body="limit" type="number" default={10}>
  How many facet values to retrieve.

  [`showMore`](#param-show-more) and [`showMoreLimit`](#param-show-more-limit) determine the number of facet values to display before clicking the Show more button.

  ```jsx JavaScript icon=code theme={"system"}
  const menuApi = useMenu({
    // ...
    limit: 5,
  });
  ```
</ParamField>

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

  ```jsx JavaScript icon=code theme={"system"}
  const menuApi = useMenu({
    // ...
    showMore: true,
  });
  ```
</ParamField>

<ParamField body="showMoreLimit" type="number">
  The maximum number of items to display if the widget is showing more than the [`limit`](#param-limit) items.

  ```jsx JavaScript icon=code theme={"system"}
  const menuApi = useMenu({
    // ...
    showMoreLimit: 20,
  });
  ```
</ParamField>

<ParamField body="sortBy" type="string[] | (a: FacetValue, b: FacetValue) => number" default="['isRefined', '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).

  If you leave the default setting for 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.

  <CodeGroup>
    ```jsx String theme={"system"}
    const menuApi = useMenu({
      // ...
      sortBy: ["count:desc", "name:asc"],
    });
    ```

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

    function Menu() {
      const menuApi = useMenu({
        // ...
        sortBy,
      });

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

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

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

    function Menu() {
      const menuApi = useMenu({
        // ...
        sortBy,
      });

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

<ParamField body="transformItems" type="(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](/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`.

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

    function Menu() {
      const menuApi = useMenu({
        // ...
        transformItems,
      });

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

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

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

    function Menu() {
      const menuApi = useMenu({
        // ...
        transformItems,
      });

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

### APIs

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

<ParamField body="items" type="MenuItem[]">
  The elements that can be refined for the current search results.

  ```ts theme={"system"}
  type MenuItem = {
    /**
     * The value of the menu item.
     */
    value: string;
    /**
     * Human-readable value of the menu item.
     */
    label: string;
    /**
     * Number of matched results after refinement is applied.
     */
    count: number;
    /**
     * Indicates if the menu item is refined.
     */
    isRefined: boolean;
  };
  ```
</ParamField>

<ParamField body="createURL" type="(value: string) => string">
  Creates the next state URL of a selected refinement.
</ParamField>

<ParamField body="refine" type="(value: string) => string">
  Applies the selected refinement.
</ParamField>

<ParamField body="canRefine" type="boolean">
  Whether a refinement can be applied.
</ParamField>

<ParamField body="isShowingMore" type="boolean">
  Whether the menu is displaying all the menu items.
</ParamField>

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

<ParamField body="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`](/doc/api-reference/widgets/menu/react#param-limit) items.
</ParamField>

<ParamField body="sendEvent" type="(eventType: string, facetValue: string, eventName?: string) => void">
  Sends an event to the Insights middleware.
</ParamField>

### Example

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React from "react";
  import { useMenu } from "react-instantsearch";

  function CustomMenu(props) {
    const {
      items,
      refine,
      createURL,
      canToggleShowMore,
      toggleShowMore,
      isShowingMore,
    } = useMenu(props);

    return (
      <>
        <ul>
          {items.map((item) => (
            <li key={item.label}>
              <a
                href={createURL(item.value)}
                onClick={(event) => {
                  event.preventDefault();

                  refine(item.value);
                }}
                style={{ fontWeight: item.isRefined ? "bold" : "normal" }}
              >
                <span>{item.label}</span>
                <span>{item.count}</span>
              </a>
            </li>
          ))}
        </ul>
        {props.showMore && (
          <button disabled={!canToggleShowMore} onClick={toggleShowMore}>
            {isShowingMore ? "Show less" : "Show more"}
          </button>
        )}
      </>
    );
  }
  ```

  ```tsx TypeScript theme={"system"}
  import React from 'react';
  import { useMenu, UseMenuProps } from 'react-instantsearch';

  function CustomMenu(props: UseMenuProps) {
    const {
      items,
      refine,
      createURL,
      canToggleShowMore,
      toggleShowMore,
      isShowingMore,
    } = useMenu(props);

    return (
      <>
        <ul>
          {items.map((item) => (
            <li key={item.label}>
              <a
                href={createURL(item.value)}
                onClick={(event) => {
                  event.preventDefault();

                  refine(item.value);
                }}
                style={{ fontWeight: item.isRefined ? 'bold' : 'normal' }}
              >
                <span>{item.label}</span>
                <span>{item.count}</span>
              </a>
            </li>
          ))}
        </ul>
        {props.showMore && (
          <button disabled={!canToggleShowMore} onClick={toggleShowMore}>
            {isShowingMore ? 'Show less' : 'Show more'}
          </button>
        )}
      </>
    );
  }
  ```
</CodeGroup>
