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

# infiniteHits

> Shows search results with a button to load more.

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

## Import

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

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

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

## About this widget

The `infiniteHits` widget displays a list of results with a "Show more" button at the bottom of the list.
As an alternative to this approach, [the infinite scroll guide](/doc/guides/building-search-ui/ui-and-ux-patterns/infinite-scroll/js)
describes how to create an automatically scrolling infinite hits experience.

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

See also: [Searches without results](/doc/guides/building-search-ui/going-further/conditional-display/js#handling-no-results)

## Examples

```js JavaScript icon=code theme={"system"}
infiniteHits({
  container: "#infinite-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"}
    infiniteHits({
      container: '#infinite-hits',
    });
    ```

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

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

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

<ParamField body="showPrevious" type="boolean" default={false}>
  Enable the button to load previous results.

  The button is only displayed if the routing option is enabled in [`instantsearch`](/doc/api-reference/widgets/instantsearch/js#param-routing) and users aren't on the first page.
  Override this behavior with [connectors](#customize-the-ui-with-connectinfinitehits).

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

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

  ```js JavaScript icon=code theme={"system"}
  infiniteHits({
    // ...
    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 root container without results.
  * `list`. The list of results.
  * `item`. The list item.
  * `loadPrevious`. The "Show previous" button.
  * `loadMore`. The "Show more" button.
  * `disabledLoadPrevious`. The disabled "Show previous" button.
  * `disabledLoadMore`. The disabled "Show more" button.
  * `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"}
  infiniteHits({
    // ...
    cssClasses: {
      root: "MyCustomInfiniteHits",
      list: ["MyCustomInfiniteHits", "MyCustomInfiniteHits--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`.

  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"}
  infiniteHits({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        name: item.name.toUpperCase(),
      }));
    },
  });

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

<ParamField body="cache" type="object">
  The widget caches all loaded hits.
  By default, it uses its own internal in-memory cache implementation.
  Alternatively, use [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)
  to retain the cache even if users reload the page.

  You can also implement your own cache object with `read` and `write` methods.
  This can be handy if you need to persist the data across sessions or if you expect the cached data to grow larger than the browser's [5 MB allowed storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria#web_storage).

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

    const sessionStorageCache = createInfiniteHitsSessionStorageCache();

    infiniteHits({
      // ...
      cache: sessionStorageCache,
    });
    ```

    ```js CDN theme={"system"}
    const { createInfiniteHitsSessionStorageCache } = instantsearch;
    // or directly use instantsearch.createInfiniteHitsSessionStorageCache()

    const sessionStorageCache = createInfiniteHitsSessionStorageCache();

    infiniteHits({
      // ...
      cache: sessionStorageCache,
    });
    ```

    ```js custom theme={"system"}
    const customCache = {
      read({ state }) {
        const { cachedKey, cachedHits } = // read from your cache
        const currentKey = convertStateToKey(state);
        if (isEqual(cachedKey, currentKey)) {
          return cachedHits;
        } else {
          return null;
        }
      },
      write({ state, hits }) {
        const currentKey = convertStateToKey(state);
        // write in your cache
      },
    }

    function isEqual(obj1, obj2) {
      // perform deep equal
    }

    function convertStateToKey(state) {
      const { page, ...rest } = state || {};
      // Regardless of the `page`,
      // check if the rest of the state is the same.
      return rest;
    }

    infiniteHits({
      // ...
      cache: customCache
    });
    ```
  </CodeGroup>
</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"}
    infiniteHits({
      // ...
      templates: {
        empty(results, { html }) {
          return html`<p>No results <q>${results.query}</q></p>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    infiniteHits({
      // ...
      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`](/doc/api-reference/widgets/highlight/js) function, directly from the template.

  ```js JavaScript icon=code theme={"system"}
  infiniteHits({
    // ...
    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 `className` string representing the CSS classes provided to the widget.
  It is rendered above the results.

  <CodeGroup>
    ```js function theme={"system"}
    infiniteHits({
      // ...
      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.
    infiniteHits({
      // ...
      templates: {
        banner: `<img src="${banner.image.urls[0].url}" />`,
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="showPreviousText" type="string | function" default="Show previous results">
  The template to use for the "Show previous" label.

  <CodeGroup>
    ```js function theme={"system"}
    infiniteHits({
      // ...
      templates: {
        showPreviousText(data, { html }) {
          return html`<span>Show previous</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    infiniteHits({
      // ...
      templates: {
        showPreviousText: "Show previous",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="showMoreText" type="string | function" default="Show more results">
  The template to use for the "Show more" label.

  <CodeGroup>
    ```js function theme={"system"}
    infiniteHits({
      // ...
      templates: {
        showMoreText(data, { html }) {
          return html`<span>Show more</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    infiniteHits({
      // ...
      templates: {
        showMoreText: "Show more",
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-InfiniteHits">
  <button class="ais-InfiniteHits-loadPrevious">Show previous</button>
  <aside class="ais-InfiniteHits-banner">
    <a class="ais-InfiniteHits-banner-link">
      <img class="ais-InfiniteHits-banner-image" />
    </a>
  </aside>
  <ol class="ais-InfiniteHits-list">
    <li class="ais-InfiniteHits-item">...</li>
    <li class="ais-InfiniteHits-item">...</li>
    <li class="ais-InfiniteHits-item">...</li>
  </ol>
  <button class="ais-InfiniteHits-loadMore">Show more</button>
</div>
```

## Customize the UI with `connectInfiniteHits`

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

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

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

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

Then it's a 3-step process:

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

// 2. Create the custom widget
const customInfiniteHits = connectInfiniteHits(renderInfiniteHits);

// 3. Instantiate
search.addWidgets([
  customInfiniteHits({
    // 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 renderInfiniteHits = (renderOptions, isFirstRender) => {
  const {
    items,
    currentPageHits,
    results,
    banner,
    sendEvent,
    isFirstPage,
    isLastPage,
    showPrevious,
    showMore,
    widgetParams,
  } = renderOptions;

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

  // Render the widget
};
```

#### Rendering options

<ParamField body="items" type="object[]">
  The matched hits from the Algolia API.
  This returns the combined hits for all the pages that have been requested so far.
  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`](/doc/api-reference/widgets/highlight/js) function,
  directly from the connector's render function.

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

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

<ParamField body="currentPageHits" type="object[]">
  The matched hits from the Algolia API for the current page.
  Unlike the `hits` parameter, this only returns the hits for the currently requested page.
  This can be useful if you want to handle how the new page of hits is going to be added to the list of search results.
  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`](/doc/api-reference/widgets/highlight/js) function,
  directly from the connector's render function.

  ```js JavaScript icon=code theme={"system"}
  const renderInfiniteHits = (renderOptions, isFirstRender) => {
    const { currentPageHits } = renderOptions;
    const container = document.querySelector('#infinite-hits');

    if (isFirstRender) {
      const ul = document.createElement('ul');
      container.appendChild(ul);

      return;
    }

    container.querySelector('ul').insertAdjacentHTML('beforeend', currentPageHits
      .map(
        hit =>
          `<li>
            ${instantsearch.highlight({ attribute: 'name', hit: item })}
          </li>`
      )
      .join(''));
  };
  ```
</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`](/doc/api-reference/widgets/stats/js) widget if you want to build a widget that displays metadata about the search.

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

    if (isFirstRender) {
      return;
    }

    document.querySelector('#infinite-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('#infinite-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 items.

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

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

  ```js JavaScript icon=code 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.infiniteHits',
    }
  */
  ```
</ParamField>

<ParamField body="isFirstPage" type="boolean">
  Indicates whether the first page of hits has been reached.

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

    document.querySelector('#infinite-hits').innerHTML = `
      <button ${isFirstPage ? 'disabled' : ''}>
        Static "Show previous" button
      </button>
      <ul>
        ${items.map(item => `<li>${item.name}</li>`).join('')}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="isLastPage" type="boolean">
  Indicates whether the last page of hits has been reached.

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

    document.querySelector('#infinite-hits').innerHTML = `
      <ul>
        ${items.map(item => `<li>${item.name}</li>`).join('')}
      </ul>
      <button ${isLastPage ? 'disabled' : ''}>
        Static "Show more" button
      </button>
    `;
  };
  ```
</ParamField>

<ParamField body="showPrevious" type="function">
  Loads the previous page of hits.

  ```js JavaScript icon=code theme={"system"}
  const renderInfiniteHits = (renderOptions, isFirstRender) => {
    const { items, showPrevious } = renderOptions;
    const container = document.querySelector('#infinite-hits');

    if (isFirstRender) {
      const ul = document.createElement('ul');
      const button = document.createElement('button');
      button.textContent = 'Show previous';

      button.addEventListener('click', () => {
        showPrevious();
      });

      container.appendChild(button);
      container.appendChild(ul);

      return;
    }

    container.querySelector('ul').innerHTML = `
      ${items.map(item => `<li>${item.name}</li>`).join('')}
    `;
  };
  ```
</ParamField>

<ParamField body="showMore" type="function">
  Loads the next page of hits.

  ```js JavaScript icon=code theme={"system"}
  const renderInfiniteHits = (renderOptions, isFirstRender) => {
    const { items, showMore } = renderOptions;
    const container = document.querySelector('#infinite-hits');

    if (isFirstRender) {
      const ul = document.createElement('ul');
      const button = document.createElement('button');
      button.textContent = 'Show more';

      button.addEventListener('click', () => {
        showMore();
      });

      container.appendChild(ul);
      container.appendChild(button);

      return;
    }

    container.querySelector('ul').innerHTML = `
      ${items.map(item => `<li>${item.name}</li>`).join('')}
    `;
  };
  ```
</ParamField>

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

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

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

  // ...

  search.addWidgets([
    customInfiniteHits({
      container: document.querySelector('#infinite-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 customInfiniteHits = connectInfiniteHits(
  renderInfiniteHits
);

search.addWidgets([
  customInfiniteHits({
    // Optional parameters
    escapeHTML: boolean,
    showPrevious: boolean,
    transformItems: function,
  })
]);
```

#### Instance options

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

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

<ParamField body="showPrevious" type="boolean" default={false}>
  Enable the button to load previous results.

  ```js JavaScript icon=code theme={"system"}
  customInfiniteHits({
    showPrevious: true,
  });
  ```
</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`.

  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"}
  customInfiniteHits({
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        name: item.name.toUpperCase(),
      }));
    },
  });

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

### Full example

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

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

    if (isFirstRender) {
      const ul = document.createElement("ul");
      const previousButton = document.createElement("button");
      previousButton.className = "previous-button";
      previousButton.textContent = "Show previous";

      previousButton.addEventListener("click", () => {
        showPrevious();
      });

      const nextButton = document.createElement("button");
      nextButton.className = "next-button";
      nextButton.textContent = "Show more";

      nextButton.addEventListener("click", () => {
        showMore();
      });

      widgetParams.container.appendChild(previousButton);
      widgetParams.container.appendChild(ul);
      widgetParams.container.appendChild(nextButton);

      return;
    }

    widgetParams.container.querySelector(".previous-button").disabled =
      isFirstPage;
    widgetParams.container.querySelector(".next-button").disabled = isLastPage;

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

  // Create the custom widget
  const customInfiniteHits = connectInfiniteHits(renderInfiniteHits);

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

## Click and conversion events

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

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

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"}
infiniteHits({
  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"}
infiniteHits({
  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 this item were added
                    quantity: 2,
                  },
                ],
                // 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)
