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

# hierarchicalMenu

> Shows a hierarchical menu to navigate nested categories.

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

```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()
```

> [card] [See this widget in action](https://instantsearchjs.netlify.app/examples/js/showcase/?view=reference\&flavor=js\&widget=hierarchicalMenu)
>
> Preview this widget and its behavior.

## 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](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting#hierarchical-facets)
2. Determine your [`attributes`](#param-attributes) for faceting from the [dashboard](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting-with-dashboard.md) or with an [API client](https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/how-to/declaring-attributes-for-faceting.md)
3. Display the UI with the hierarchical menu widget.

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

### 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`](https://www.algolia.com/doc/api-reference/widgets/instantsearch/js#param-future-persist-hierarchical-root-count) in [`instantsearch`](https://www.algolia.com/doc/api-reference/widgets/instantsearch/js).

## Examples

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

## Options

**container** `string | HTMLElement` *required*

The CSS Selector or `HTMLElement` to insert the widget into.

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

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

**attributes** `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",
  ],
});
```

**limit** `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,
});
```

**showMore** `boolean` (default: false)

Whether to display a button that expands the number of items.

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

**showMoreLimit** `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,
});
```

**separator** `string` (default: >)

The level separator used in the records (A record is a searchable object in an Algolia index. Each record consists of named attributes.).

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

**rootPath** `string` (default: null)

The prefix path to use if the first level isn't the root level.

Make sure to also include the root path in your [UI state](https://www.algolia.com/doc/api-reference/widgets/ui-state/js.md),
for example, by setting [`initialUiState`](https://www.algolia.com/doc/api-reference/widgets/instantsearch/js#param-initial-ui-state)
or calling [`setUiState()`](https://www.algolia.com/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",
  }),
]);
```

**showParentLevel** `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,
});
```

**sortBy** `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).

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

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

**templates** `object`

The [templates](#templates) to use for the widget.

```js JavaScript icon=code theme={"system"}
hierarchicalMenu({
  // ...
  templates: {
    // ...
  },
});
```

**cssClasses** `object` (default: \{})

The [CSS classes you can override](https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js.md#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 "Show more" button when it's unavailable.

```js JavaScript icon=code theme={"system"}
hierarchicalMenu({
  // ...
  cssClasses: {
    root: "MyCustomHierarchicalMenu",
    list: [
      "MyCustomHierarchicalMenuList",
      "MyCustomHierarchicalMenuList--subclass",
    ],
  },
});
```

**transformItems** `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](https://www.algolia.com/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/js.md)
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,
    }));
  },
});
```

## 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](https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js.md#templating-your-ui).

> [!NOTE]
>
> The `html` function is available in InstantSearch.js version 4.46.0 or later.

**item** `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.

```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>
    `,
  },
});
```

**showMoreText** `string | function`

The template for the "Show more" button text. It exposes:

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

```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}}
    `,
  },
});
```

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

```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()
```

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](https://www.algolia.com/doc/guides/building-search-ui/resources/seo/js.md).

#### Rendering options

**items** `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;
};
```

**isShowingMore** `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>
  `;
};
```

**canToggleShowMore** `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>`;
};
```

**canRefine** `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;
  }
};
```

**refine** `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);
    });
  });
};
```

**sendEvent** `(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`](https://www.algolia.com/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',
  }
*/
```

**toggleShowMore** `function`

Toggles the number of displayed values between [`limit`](https://www.algolia.com/doc/api-reference/widgets/hierarchical-menu/js#param-limit) and [`showMoreLimit`](https://www.algolia.com/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";
};
```

**createURL** `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;
};
```

**widgetParams** `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'),
  })
]);
```

### Create and instantiate the custom widget

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

You can pass two kinds of parameters:

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

**attributes** `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",
  ],
});
```

**limit** `number` (default: 10)

The number of facet values to retrieve.
When [`isShowingMore`](https://www.algolia.com/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,
});
```

**showMoreLimit** `number`

The maximum number of displayed items (only used when the `showMore` feature is implemented).

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

**separator** `string` (default: >)

The level separator used in the records.

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

**rootPath** `string`

The prefix path to use if the first level isn't the root level.

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

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

**showParentLevel** `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,
});
```

**sortBy** `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.

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

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

**transformItems** `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](https://www.algolia.com/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/js.md)
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,
    }));
  },
});
```

### Full example

```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,
  }),
]);
```
