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

# hierarchicalMenu

> Shows a hierarchical menu to navigate nested categories.

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

<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/hierarchical-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/hierarchical-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/hierarchical-menu/vue"><span className="afs-option-name">Vue</span><span className="afs-option-lib">Vue InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/hierarchical-menu/ios"><span className="afs-option-name">iOS</span><span className="afs-option-lib">InstantSearch iOS</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/hierarchical-menu/android"><span className="afs-option-name">Android</span><span className="afs-option-lib">InstantSearch Android</span></a></li>
    </ul>
  </div>
</div>

```ts Signature theme={"system"}
hierarchicalMenu({
  container: string | HTMLElement,
  attributes: string[],
  // Optional parameters
  limit?: number,
  showMore?: boolean,
  showMoreLimit?: number,
  separator?: string,
  rootPath?: string,
  showParentLevel?: boolean,
  sortBy?: string[] | function,
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});
```

## Import

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

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

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

## About this widget

The `hierarchicalMenu` widget displays a hierarchical navigation menu, based on facet attributes.

To create a hierarchical menu:

1. Decide on an appropriate [facet hierarchy](/doc/guides/managing-results/refine-results/faceting#hierarchical-facets)
2. Determine your [`attributes`](#param-attributes) for faceting from the [dashboard](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard) or with an [API client](/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting)
3. Display the UI with the hierarchical menu widget.

To learn more, see [Facet display](/doc/guides/building-search-ui/ui-and-ux-patterns/facet-display/js).

### Requirements

The objects to use in the hierarchical menu must follow this structure:

```json JSON icon=braces theme={"system"}
[
  {
    "objectID": "321432",
    "name": "lemon",
    "categories": {
      "lvl0": "products",
      "lvl1": "products > fruits"
  },
  {
    "objectID": "8976987",
    "name": "orange",
    "categories": {
      "lvl0": "products",
      "lvl1": "products > fruits"
    }
  }
]
```

You can also provide more than one path for each level:

```json JSON icon=braces theme={"system"}
[
  {
    "objectID": "321432",
    "name": "lemon",
    "categories": {
      "lvl0": ["products", "goods"],
      "lvl1": ["products > fruits", "goods > to eat"]
    }
  }
]
```

By default, the separator is `>` (with spaces), but you can use a different one by using the [`separator`](#param-separator) option.

<Note>
  By default, the count of the refined root level is updated to match the count
  of the actively refined parent level. Keep the root level count intact by
  setting
  [`persistHierarchicalRootCount`](/doc/api-reference/widgets/instantsearch/js#param-future-persist-hierarchical-root-count)
  in [`instantsearch`](/doc/api-reference/widgets/instantsearch/js).
</Note>

## Examples

```js JavaScript icon=code theme={"system"}
hierarchicalMenu({
  container: "#hierarchical-menu",
  attributes: [
    "categories.lvl0",
    "categories.lvl1",
    "categories.lvl2",
    "categories.lvl3",
  ],
});
```

## Options

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

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

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

<ParamField body="attributes" type="string[]" required>
  The name of the attributes to generate the menu with.

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

  ```js JavaScript icon=code theme={"system"}
  hierarchicalMenu({
    // ...
    attributes: [
      "categories.lvl0",
      "categories.lvl1",
      "categories.lvl2",
      "categories.lvl3",
    ],
  });
  ```
</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"}
  hierarchicalMenu({
    // ...
    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"}
  hierarchicalMenu({
    // ...
    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"}
  hierarchicalMenu({
    // ...
    showMoreLimit: 20,
  });
  ```
</ParamField>

<ParamField body="separator" type="string" default=">">
  The level separator used in the <Records />.

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

<ParamField body="rootPath" type="string" default="null">
  The prefix path to use if the first level is not the root level.

  Make sure to also include the root path in your [UI state](/doc/api-reference/widgets/ui-state/js),
  for example, by setting [`initialUiState`](/doc/api-reference/widgets/instantsearch/js#param-initial-ui-state)
  or calling [`setUiState()`](/doc/api-reference/widgets/instantsearch/js#param-set-ui-state).

  ```js JavaScript icon=code theme={"system"}
  instantsearch({
    // ...
    initialUiState: {
      YourIndexName: {
        hierarchicalMenu: {
          "categories.lvl0": ["Computers & Tablets"],
        },
      },
    },
  }).addWidgets([
    hierarchicalMenu({
      // ...
      rootPath: "Computers & Tablets",
    }),
  ]);
  ```
</ParamField>

<ParamField body="showParentLevel" type="boolean" default={true}>
  Whether to show the siblings of the selected parent level of the current refined value.

  This option doesn't impact the root level. All root items are always visible.

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

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

  You can also 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).

  <CodeGroup>
    ```js string[] theme={"system"}
    hierarchicalMenu({
      // ...
      sortBy: ['isRefined'],
    });
    ```

    ```js function theme={"system"}
    hierarchicalMenu({
      // ...
      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"}
  hierarchicalMenu({
    // ...
    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`. The root element if there are no refinements.
  * `list`. The list of results.
  * `childList`. The child list element.
  * `item`. The list items.
  * `selectedItem`. The selected item of the list.
  * `parentItem`. The parent item of the list.
  * `link`. The link of each item.
  * `selectedItemLink`. The link of each selected item.
  * `label`. The label of each item.
  * `count`. The count of each item.
  * `showMore`. The "Show more" button.
  * `disabledShowMore`. The disabled "Show more" button.

  ```js JavaScript icon=code theme={"system"}
  hierarchicalMenu({
    // ...
    cssClasses: {
      root: "MyCustomHierarchicalMenu",
      list: [
        "MyCustomHierarchicalMenuList",
        "MyCustomHierarchicalMenuList--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"}
  hierarchicalMenu({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        label: item.label.toUpperCase(),
      }));
    },
  });

  // or, combined with results
  hierarchicalMenu({
    // ...
    transformItems(items, { results }) {
      return items.map((item) => ({
        ...item,
        label: item.isRefined
          ? `${item.label} (page ${results.page + 1}/${results.nbPages})`
          : 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:

  * `label: string`. The label of the item.
  * `value: string`. The value of the item.
  * `count: number`. The number of results matching the value.
  * `isRefined: boolean` Whether the item is selected.
  * `url: string`. The URL with the applied refinement.

  <CodeGroup>
    ```js function theme={"system"}
    hierarchicalMenu({
      // ...
      templates: {
        item(data, { html }) {
          return html`
            <a class="${data.cssClasses.link}" href="${data.url}">
              <span class="${data.cssClasses.label}">${data.label}</span>
              <span class="${data.cssClasses.count}">
                ${data.count.toLocaleString()}
              </span>
            </a>
          `;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    hierarchicalMenu({
      // ...
      templates: {
        item: `
          <a class="{{cssClasses.link}}" href="{{url}}">
            <span class="{{cssClasses.label}}">{{label}}</span>
            <span class="{{cssClasses.count}}">
              {{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}
            </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"}
    hierarchicalMenu({
      // ...
      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.
    hierarchicalMenu({
      // ...
      templates: {
        showMoreText: `
          {{#isShowingMore}}
            Show less
          {{/isShowingMore}}
          {{^isShowingMore}}
            Show more
          {{/isShowingMore}}
        `,
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-HierarchicalMenu">
  <ul class="ais-HierarchicalMenu-list ais-HierarchicalMenu-list--lvl0">
    <li
      class="ais-HierarchicalMenu-item ais-HierarchicalMenu-item--parent ais-HierarchicalMenu-item--selected"
    >
      <a
        class="ais-HierarchicalMenu-link ais-HierarchicalMenu-link--selected"
        href="#"
      >
        <span class="ais-HierarchicalMenu-label">Appliances</span>
        <span class="ais-HierarchicalMenu-count">4,306</span>
      </a>
      <ul
        class="ais-HierarchicalMenu-list ais-HierarchicalMenu-list--child ais-HierarchicalMenu-list--lvl1"
      >
        <li class="ais-HierarchicalMenu-item ais-HierarchicalMenu-item--parent">
          <a class="ais-HierarchicalMenu-link" href="#">
            <span class="ais-HierarchicalMenu-label">Dishwashers</span>
            <span class="ais-HierarchicalMenu-count">181</span>
          </a>
        </li>
        <li class="ais-HierarchicalMenu-item">
          <a class="ais-HierarchicalMenu-link" href="#">
            <span class="ais-HierarchicalMenu-label">Fans</span>
            <span class="ais-HierarchicalMenu-count">91</span>
          </a>
        </li>
      </ul>
    </li>
    <li class="ais-HierarchicalMenu-item ais-HierarchicalMenu-item--parent">
      <a class="ais-HierarchicalMenu-link" href="#">
        <span class="ais-HierarchicalMenu-label">Audio</span>
        <span class="ais-HierarchicalMenu-count">1,570</span>
      </a>
    </li>
  </ul>
  <button class="ais-HierarchicalMenu-showMore">Show more</button>
</div>
```

## Customize the UI with `connectHierarchicalMenu`

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

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

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

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

Then it's a 3-step process:

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

// 2. Create the custom widget
const customHierarchicalMenu = connectHierarchicalMenu(renderHierarchicalMenu);

// 3. Instantiate
search.addWidgets([
  customHierarchicalMenu({
    // 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 renderHierarchicalMenu = (renderOptions, isFirstRender) => {
  const {
    items,
    isShowingMore,
    canToggleShowMore,
    canRefine,
    refine,
    sendEvent,
    toggleShowMore,
    createURL,
    widgetParams,
  } = renderOptions;

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

  // Render the widget
};
```

<Note>
  If SEO is important for your search page, ensure that your custom HTML is optimized for search engines:

  * Use `<a>` tags with `href` attributes to allow search engine bots to follow links.
  * Use semantic HTML and include [structured data](https://developers.google.com/search/docs/appearance/structured-data) when relevant.

  For more guidance, see the [SEO checklist](/doc/guides/building-search-ui/resources/seo/js).
</Note>

#### Rendering options

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

  * `label: string`. The label of the item.
  * `value: string`. The value of the item.
  * `count: number`. The number results matching this value.
  * `isRefined: boolean`. Whether the item is selected.
  * `data: object[]|null`. The list of children for the current item.

  ```js JavaScript icon=code theme={"system"}
  const renderList = (items) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a href="#">${item.label} (${item.count})</a>
              ${item.data ? renderList(item.data) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const { items } = renderOptions;

    const children = renderList(items);

    document.querySelector("#hierarchical-menu").innerHTML = children;
  };
  ```
</ParamField>

<ParamField body="isShowingMore" type="boolean">
  Whether the list is expanded.

  ```js JavaScript icon=code theme={"system"}
  const renderList = (items) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a href="#">${item.label} (${item.count})</a>
              ${item.data ? renderList(item.data) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const { items, isShowingMore } = renderOptions;

    document.querySelector("#hierarchical-menu").innerHTML = `
      ${renderList(items)}
      <button>${isShowingMore ? "Show less" : "Show more"}</button>
    `;
  };
  ```
</ParamField>

<ParamField body="canToggleShowMore" type="boolean">
  Whether users can click the "Show more" button.

  ```js JavaScript icon=code theme={"system"}
  const renderList = (items) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a href="#">${item.label} (${item.count})</a>
              ${item.data ? renderList(item.data) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const { items, canToggleShowMore } = renderOptions;

    document.querySelector("#hierarchical-menu").innerHTML =
      `  ${renderList(items)}
      <button ${!canToggleShowMore ? "disabled" : ""}>Show more</button>`;
  };
  ```
</ParamField>

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

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

    if (!canRefine) {
      document.querySelector("#hierarchical-menu").innerHTML = "";
      return;
    }
  };
  ```
</ParamField>

<ParamField body="refine" type="function">
  Sets the path of the hierarchical filter and triggers a new search.

  ```js JavaScript icon=code theme={"system"}
  const renderList = (items) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a
                href="#"
                data-value="${item.value}"
                style="font-weight: ${item.isRefined ? "bold" : ""}"
              >
                ${item.label} (${item.count})
              </a>
              ${item.data ? renderList(item.data) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const { items, refine } = renderOptions;

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

    container.innerHTML = renderList(items);

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

<ParamField body="sendEvent" type="(eventType, facetValue) => void">
  The function to send `click` events.

  * The `view` event is automatically sent when the facets are rendered.
  * The `click` event is automatically sent when `refine` is called.
  * You can learn more about the [`insights`](/doc/api-reference/widgets/insights/js) middleware.
  * `eventType: 'click'`
  * `facetValue: string`

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

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

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

  ```js JavaScript icon=code theme={"system"}
  const renderList = (items) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a href="#">${item.label} (${item.count})</a>
              ${item.data ? renderList(item.data) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const { items, isShowingMore, toggleShowMore } = renderOptions;

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

    if (isFirstRender) {
      const list = document.createElement("div");
      const button = document.createElement("button");

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

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

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

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

  ```js JavaScript icon=code theme={"system"}
  const renderList = ({ items, createURL }) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a href="${createURL(item.value)}">
                ${item.label} (${item.count})
              </a>
              ${item.data ? renderList({ items: item.data, createURL }) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const { items, createURL } = renderOptions;

    const children = renderList({ items, createURL });

    document.querySelector("#hierarchical-menu").innerHTML = children;
  };
  ```
</ParamField>

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

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

    widgetParams.container.innerHTML = '...';
  };

  // ...

  search.addWidgets([
    customHierarchicalMenu({
      // ...
      container: document.querySelector('#hierarchical-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`.

```jsx JavaScript icon=code theme={"system"}
const customHierarchicalMenu = connectHierarchicalMenu(
  renderHierarchicalMenu
);

search.addWidgets([
  customHierarchicalMenu({
    attributes: string[],
    // Optional parameters
    limit?: number,
    showMoreLimit?: number,
    separator?: string,
    rootPath?: string,
    showParentLevel?: boolean,
    sortBy?: string[] | function,
    transformItems?: function,
  })
]);
```

#### Instance options

<ParamField body="attributes" type="string[]" required>
  The name of the attributes to generate the menu with.

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

  ```js JavaScript icon=code theme={"system"}
  customHierarchicalMenu({
    attributes: [
      "categories.lvl0",
      "categories.lvl1",
      "categories.lvl2",
      "categories.lvl3",
    ],
  });
  ```
</ParamField>

<ParamField body="limit" type="number" default={10}>
  The number of facet values to retrieve.
  When [`isShowingMore`](/doc/api-reference/widgets/hierarchical-menu/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"}
  customHierarchicalMenu({
    // ...
    limit: 5,
  });
  ```
</ParamField>

<ParamField body="showMoreLimit" type="number">
  The maximum number of displayed items (only used when the `showMore` feature is implemented).

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

<ParamField body="separator" type="string" default=">">
  The level separator used in the records.

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

<ParamField body="rootPath" type="string">
  The prefix path to use if the first level is not the root level.

  Make sure to also include the root path in your [UI state](/doc/api-reference/widgets/ui-state/js),
  for example, by setting [`initialUiState`](/doc/api-reference/widgets/instantsearch/js#param-initial-ui-state)
  or calling [`setUiState()`](/doc/api-reference/widgets/instantsearch/js#param-set-ui-state).

  ```js JavaScript icon=code theme={"system"}
  customHierarchicalMenu({
    // ...
    rootPath: "Computers & Tablets",
  });
  ```
</ParamField>

<ParamField body="showParentLevel" type="boolean" default={true}>
  Whether to show the siblings of the selected parent level of the current refined value.

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

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

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

  You can also give a function that 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.

  <CodeGroup>
    ```js string[] theme={"system"}
    customHierarchicalMenu({
      // ...
      sortBy: ['isRefined'],
    });
    ```

    ```js function theme={"system"}
    customHierarchicalMenu({
      // ...
      sortBy(a, b) {
        return a.name < b.name ? 1 : -1;
      },
    });
    ```
  </CodeGroup>
</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"}
  customHierarchicalMenu({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        label: item.label.toUpperCase(),
      }));
    },
  });

  /* or, combined with results */
  customHierarchicalMenu({
    // ...
    transformItems(items, { results }) {
      return items.map((item) => ({
        ...item,
        label: item.isRefined
          ? `${item.label} (page ${results.page + 1}/${results.nbPages})`
          : item.label,
      }));
    },
  });
  ```
</ParamField>

### Full example

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

  ```js JavaScript theme={"system"}
  // Create the render function
  const renderList = ({ items, createURL }) => `
    <ul>
      ${items
        .map(
          (item) => `
            <li>
              <a
                href="${createURL(item.value)}"
                data-value="${item.value}"
                style="font-weight: ${item.isRefined ? "bold" : ""}"
              >
                ${item.label} (${item.count})
              </a>
              ${item.data ? renderList({ items: item.data, createURL }) : ""}
            </li>
          `,
        )
        .join("")}
    </ul>
  `;

  const renderHierarchicalMenu = (renderOptions, isFirstRender) => {
    const {
      items,
      isShowingMore,
      refine,
      toggleShowMore,
      createURL,
      widgetParams,
    } = renderOptions;

    if (isFirstRender) {
      const list = document.createElement("div");
      const button = document.createElement("button");

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

      widgetParams.container.appendChild(list);
      widgetParams.container.appendChild(button);
    }

    const children = renderList({ items, createURL });

    widgetParams.container.querySelector("div").innerHTML = children;
    widgetParams.container.querySelector("button").textContent = isShowingMore
      ? "Show less"
      : "Show more";

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

  // Create the custom widget
  const customHierarchicalMenu = connectHierarchicalMenu(renderHierarchicalMenu);

  // Instantiate the custom widget
  search.addWidgets([
    customHierarchicalMenu({
      container: document.querySelector("#hierarchical-menu"),
      attributes: [
        "categories.lvl0",
        "categories.lvl1",
        "categories.lvl2",
        "categories.lvl3",
      ],
      limit: 5,
      showMoreLimit: 10,
    }),
  ]);
  ```
</CodeGroup>
