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

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" 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>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="react"
    baseHref="/doc/api-reference/widgets/menu"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
]}
  />
</div>

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