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

# hits

> Shows a list of search results.

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="js"
    baseHref="/doc/api-reference/widgets/hits"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
{ value: "ios", label: "iOS", description: "InstantSearch iOS" },
{ value: "android", label: "Android", description: "InstantSearch Android" },
]}
  />
</div>

```ts Signature theme={"system"}
hits({
  container: string | HTMLElement,
  // Optional parameters
  escapeHTML?: boolean,
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});
```

## Import

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

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

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

## About this widget

Use the `hits` widget to display a list of search results.

To set the number of search results,
use the [`hitsPerPage`](/doc/api-reference/widgets/hits-per-page/js)
or [`configure`](/doc/api-reference/widgets/configure/js) widget.

See also:

* [Structured results](/doc/guides/building-search-ui/ui-and-ux-patterns/structured-results/js)
* [Multi-index search](/doc/guides/building-search-ui/ui-and-ux-patterns/multi-index-search/js)
* [Searches without results](/doc/guides/building-search-ui/going-further/conditional-display/js#handling-no-results)

## Examples

```js JavaScript icon=code theme={"system"}
hits({
  container: "#hits",
  templates: {
    item(hit, { html, components }) {
      return html`
        <h2>${components.Highlight({ attribute: "name", hit })}</h2>
        <p>${hit.description}</p>
      `;
    },
  },
});
```

## Options

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

  <CodeGroup>
    ```js string theme={"system"}
    hits({
      container: "#hits",
    });
    ```

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

<ParamField body="escapeHTML" type="boolean" default={true}>
  Escapes HTML entities from hits string values.

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

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

  ```js JavaScript icon=code theme={"system"}
  hits({
    // ...
    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 widget's root element.
  * `emptyRoot`. The container element without results.
  * `list`. The list of results.
  * `item`. The list of items.
  * `bannerRoot`. The root element of the banner.
  * `bannerImage`. The image element of the banner.
  * `bannerLink`. The anchor element of the banner.

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

<ParamField body="transformItems" type="function" post={["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`.

  If you transform an attribute used in the [`highlight`](/doc/api-reference/widgets/highlight/js) widget,
  you must also transform the corresponding `item._highlightResult[attribute].value`.

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

  // or, combined with results
  hits({
    // ...
    transformItems(items, { results }) {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    },
  });
  ```
</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="empty" type="string | function">
  The template to use when there are no results. It exposes the `results` object.

  <CodeGroup>
    ```js function theme={"system"}
    hits({
      // ...
      templates: {
        empty(results, { html }) {
          return html`No results for <q>${results.query}</q>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    hits({
      // ...
      templates: {
        empty: "No results for <q>{{ query }}</q>",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="item" type="string | function">
  The template to use for each result.
  This template receives an object containing a single record.
  The record has a new property `__hitIndex` for the relative position of the record in the list of displayed hits.
  You can use [Algolia's highlighting feature](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#highlight-and-snippet-your-search-results) with the [`highlight`]() function, directly from the [template system](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#templating-your-ui).

  ```js JavaScript icon=code theme={"system"}
  hits({
    // ...
    templates: {
      item(hit, { html, components }) {
        return html`
          <h2>
            ${hit.__hitIndex}: ${components.Highlight({ attribute: "name", hit })}
          </h2>
          <p>${hit.description}</p>
        `;
      },
    },
  });
  ```
</ParamField>

<ParamField body="banner" type="string | function">
  The template to use for the banner.
  This template receives an object containing the `banner` data returned within the `renderingContent` property from the Algolia API response and a `classNames` object representing the CSS classes provided to the widget.
  It is rendered above the results.

  <CodeGroup>
    ```js function theme={"system"}
    hits({
      // ...
      templates: {
        banner({ banner }, { html }) {
          return html`<img src="${banner.image.urls[0].url}" />`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    hits({
      // ...
      templates: {
        banner: `<img src="${banner.image.urls[0].url}" />`,
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-Hits">
  <aside class="ais-Hits-banner">
    <a class="ais-Hits-banner-link">
      <img class="ais-Hits-banner-image" />
    </a>
  </aside>
  <ol class="ais-Hits-list">
    <li class="ais-Hits-item">...</li>
    <li class="ais-Hits-item">...</li>
    <li class="ais-Hits-item">...</li>
  </ol>
</div>
```

## Customize the UI with `connectHits`

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

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

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

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

Then it's a 3-step process:

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

// 2. Create the custom widget
const customHits = connectHits(renderHits);

// 3. Instantiate
search.addWidgets([
  customHits({
    // 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 renderHits = (renderOptions, isFirstRender) => {
  const { items, results, banner, sendEvent, widgetParams } = renderOptions;

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

  // Render the widget
};
```

#### Render options

<ParamField body="items" type="object[]">
  The matched hits from the Algolia API. You can use [Algolia's highlighting feature](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#highlight-and-snippet-your-search-results) with the [`highlight`]() function, directly from the connector's render function.

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

    document.querySelector("#hits").innerHTML = `
      <ul>
        ${items
          .map(
            (item) =>
              `<li>
                ${instantsearch.highlight({ attribute: "name", hit: item })}
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="results" type="object">
  The complete response from the Algolia API. It contains the `hits`, metadata about the page, the number of hits, and so on. Unless you need to access metadata, use `items` instead. You should also consider the [`stats`]() widget if you want to build a widget that displays metadata about the search.

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

    if (isFirstRender) {
      return;
    }

    document.querySelector("#hits").innerHTML = `
      <ul>
        ${results.hits.map((item) => `<li>${item.name}</li>`).join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="banner" type="object">
  The banner data returned within the `renderingContent` property from the Algolia API response. It is rendered above the results by default and can be used to display promotional content.

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

    document.querySelector("#hits").innerHTML = `
      <img src="${banner.image.urls[0].url}" />
      <ul>
        ${items
          .map(
            (item) =>
              `<li>
                ${instantsearch.highlight({ attribute: "name", hit: item })}
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="sendEvent" type="(eventType, hit, eventName) => void">
  The function to send `click` or `conversion` events.
  The `view` event is automatically sent when this connector renders hits.

  * `eventType: 'click' | 'conversion'`
  * `hit: Hit | Hit[]`
  * `eventName: string`

  For more about these events, see the [`insights`](/doc/api-reference/widgets/insights/js) middleware documentation.

  ```js Example theme={"system"}
  // For example,
  sendEvent("click", hit, "Product Added");
  // or
  sendEvent("conversion", hit, "Order Completed");

  /*
    A payload like the following will be sent to the `insights` middleware.
    {
      eventType: 'click',
      insightsMethod: 'clickedObjectIDsAfterSearch',
      payload: {
        eventName: 'Product Added',
        index: '<index-name>',
        objectIDs: ['<object-id>'],
        positions: [<position>],
        queryID: '<query-id>',
      },
      widgetType: 'ais.hits',
    }
  */
  ```
</ParamField>

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

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

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

  // ...

  search.addWidgets([
    customHits({
      container: document.querySelector("#hits"),
    }),
  ]);
  ```
</ParamField>

### Create and instantiate the custom widget

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

There are two kinds of parameters you can pass:

* **Instance parameters**. Predefined options that configure Algolia's behavior.
* **Custom parameters**. Parameters you define to make the widget reusable and adaptable.

Inside the `renderFunction`, both instance and custom parameters are accessible through `connector.widgetParams`.

```js JavaScript icon=code theme={"system"}
const customHits = connectHits(renderHits);

search.addWidgets([
  customHits({
    // Optional parameters
    escapeHTML,
    transformItems,
  }),
]);
```

#### Instance options

<ParamField body="escapeHTML" type="boolean" default={true}>
  Escapes HTML entities from hits string values.

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

<ParamField body="transformItems" type="function" post={["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`.

  If you transform an attribute used in the [`highlight`](/doc/api-reference/widgets/highlight/js) widget,
  you must also transform the corresponding `item._highlightResult[attribute].value`.

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

  // or: combined with results
  customHits({
    transformItems(items, { results }) {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    },
  });
  ```
</ParamField>

### Full example

<CodeGroup>
  ```html HTML theme={"system"}
  <div id="hits"></div>
  ```

  ```js JavaScript theme={"system"}
  // Create the render function
  const renderHits = (renderOptions, isFirstRender) => {
    const { items, widgetParams } = renderOptions;

    widgetParams.container.innerHTML = `
      <ul>
        ${items
          .map(
            (item) =>
              `<li>
                ${instantsearch.highlight({ attribute: "name", hit: item })}
              </li>`,
          )
          .join("")}
      </ul>
    `;
  };

  // Create the custom widget
  const customHits = connectHits(renderHits);

  // Instantiate the custom widget
  search.addWidgets([
    customHits({
      container: document.querySelector("#hits"),
    }),
  ]);
  ```
</CodeGroup>

## Click and conversion events

If the [`insights`](/doc/api-reference/widgets/instantsearch/js#param-insights) option is `true`,
the `hits` widget automatically sends a `click` event with the following shape to the Insights API whenever users click a hit.

```jsonc JSON icon=braces theme={"system"}
{
  "eventType": "click",
  "insightsMethod": "clickedObjectIDsAfterSearch",
  "payload": {
    "eventName": "Hit Clicked"
    // …
  },
  "widgetType": "ais.hits"
}
```

To customize this event, use the `sendEvent` function in your [`item`](#param-item) template and send a custom `click` event.

```js JavaScript icon=code theme={"system"}
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <div onClick="${() => sendEvent("click", hit, "Product Clicked")}">
          <h2>${components.Highlight({ attribute: "name", hit })}</h2>
          <p>${hit.description}</p>
        </div>
      `;
    },
  },
});
```

The `sendEvent` function also accepts an object as a fourth argument to send directly to the Insights API.
You can use it, for example, to send special `conversion` events with a subtype.

```js JavaScript icon=code theme={"system"}
hits({
  templates: {
    item(hit, { html, components, sendEvent }) {
      return html`
        <div>
          <h2>${components.Highlight({ attribute: "name", hit })}</h2>
          <p>${hit.description}</p>
          <button
            onClick=${() =>
              sendEvent("conversion", hit, "Added To Cart", {
                // Special subtype
                eventSubtype: "addToCart",
                // An array of objects representing each item added to the cart
                objectData: [
                  {
                    // The discount value for this item, if applicable
                    discount: hit.discount || 0,
                    // The price value for this item (minus the discount)
                    price: hit.price,
                    // How many of these items were added
                    quantity: 2,
                    // The per-item `queryID` for the query preceding this event
                    queryID: hit.__queryID,
                  },
                ],
                // The total value of all items
                value: hit.price * 2,
                // The currency code
                currency: "USD",
              })}
          >
            Add to cart
          </button>
        </div>
      `;
    },
  },
});
```

<Note>
  Use strings to represent monetary values in major currency units (for example, '5.45').
  This avoids floating-point rounding issues, especially when performing calculations.
</Note>

See also: [Send click and conversion events with InstantSearch.js](/doc/guides/building-search-ui/events/js)
