> ## 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="react"
    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>

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
  If you were using React InstantSearch Hooks,
  this v7 documentation applies—just check for [necessary changes](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
  To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).
</Note>

```tsx Signature theme={"system"}
<Hits
  // Optional props
  hitComponent={({ hit }) => JSX.Element}
  classNames={object}
  ...props={ComponentProps<'div'>}
/>
```

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

## Import

```jsx JavaScript icon=code theme={"system"}
import { Hits } from "react-instantsearch";
```

## 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/react) widget
or pass the [`hitsPerPage`](/doc/api-reference/api-parameters/hitsPerPage) prop to the
[`<Configure>`](/doc/api-reference/widgets/configure/react) widget.

See also:

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

<Tip>You can also create your own UI with [`useHits`](#hook).</Tip>

## Examples

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React from "react";
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import { InstantSearch, Hits } from "react-instantsearch";

  const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

  function Hit({ hit }) {
    return JSON.stringify(hit);
  }

  function App() {
    return (
      <InstantSearch indexName="instant_search" searchClient={searchClient}>
        <Hits hitComponent={Hit} />
      </InstantSearch>
    );
  }
  ```

  ```tsx TypeScript theme={"system"}
  import React from "react";
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import { InstantSearch, Hits } from "react-instantsearch";
  import type { Hit as AlgoliaHit } from "instantsearch.js";

  const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

  type MyHit = AlgoliaHit<{
    name: string;
  }>;

  function Hit({ hit }: { hit: MyHit }) {
    return JSON.stringify(hit);
  }

  function App() {
    return (
      <InstantSearch indexName="instant_search" searchClient={searchClient}>
        <Hits<MyHit> hitComponent={Hit} />
      </InstantSearch>
    );
  }
  ```
</CodeGroup>

## Props

<ParamField body="hitComponent" type="(props: { hit: THit; sendEvent: SendEventForHits }) => JSX.Element">
  A component that renders each hit from the results.
  It receives a `hit` and a `sendEvent` (for [`insights`](/doc/api-reference/widgets/insights/react)) prop.

  When not provided, the widget displays the hit as a JSON string.

  ```jsx JavaScript icon=code theme={"system"}
  <Hits hitComponent={({ hit }) => hit.objectID} />;
  ```
</ParamField>

<ParamField body="bannerComponent" type="((props: { banner: SearchResults['renderingContent']['widgets']['banners'][0] }) => JSX.Element) | false">
  A component that renders the banner data on the `renderingContent` property from the Algolia response.
  It overrides the default banner rendering.

  When `false`, the widget does not render the banner.

  ```jsx JavaScript icon=code theme={"system"}
  // Override the default banner rendering
  <Hits
    // ...
    bannerComponent={({ banner }) => <img src={banner.image.urls[0].url} />}
  />

  // Disable the banner rendering

  <Hits
    // ...
    bannerComponent={false}
  />
  ```
</ParamField>

<ParamField body="escapeHTML" type="boolean" default={true}>
  Whether to escape HTML tags from hits string values.

  ```jsx JavaScript icon=code theme={"system"}
  <Hits
    // ...
    escapeHTML={false}
  />;
  ```
</ParamField>

<ParamField body="transformItems" type="(items: object[], metadata: { results: SearchResults }) => object[]">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

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

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    // Using only items
    const transformItems = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems = (items, { results }) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function Search() {
      return (
        <Hits
          // ...
          transformItems={transformItems}
        />
      );
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { HitsProps } from "react-instantsearch";

    // Using only items
    const transformItems: HitsProps["transformItems"] = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems: HitsProps["transformItems"] = (items, { results }) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function Search() {
      return (
        <Hits
          // ...
          transformItems={transformItems}
        />
      );
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="classNames" type="Partial<HitsClassNames>">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react#style-your-widgets)
  and pass to the widget's elements.
  It's useful to style widgets with class-based CSS frameworks like [Bootstrap](https://getbootstrap.com)
  or [Tailwind CSS](https://tailwindcss.com).

  * `root`. The widget's root element.
  * `emptyRoot`. The root 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.

  ```jsx JavaScript icon=code theme={"system"}
  <Hits
    // ...
    classNames={{
      root: "MyCustomHits",
      list: "MyCustomHitsList MyCustomHitsList--subclass",
    }}
  />;
  ```
</ParamField>

<ParamField body="...props" type="React.ComponentProps<'div'>">
  Any `<div>` prop to forward to the widget's root element.

  ```jsx JavaScript icon=code theme={"system"}
  <Hits className="MyCustomHits" title="My custom title" />;
  ```
</ParamField>

## Hook

React InstantSearch let you create your own UI for the `<Hits>` widget with `useHits`.
Hooks provide APIs to access the widget state and interact with InstantSearch.

The `useHits` Hook accepts [parameters](#parameters) and returns [APIs](#hook).
It must be used inside the [`<InstantSearch>`](/doc/api-reference/widgets/instantsearch/react) component.

### Usage

First, create your React component:

```jsx JavaScript icon=code theme={"system"}
import { useHits } from "react-instantsearch";

function CustomHits(props) {
  const { items, results, banner, sendEvent } = useHits(props);

  return <>{/*Your JSX*/}</>;
}
```

Then, render the widget:

```jsx JavaScript icon=code theme={"system"}
<CustomHits {...props} />;
```

### Parameters

Hooks accept parameters. You can either pass them manually or forward props from a custom component.

<Note>
  When passing functions to Hooks, ensure stable references to prevent unnecessary re-renders.
  Use [`useCallback()`](https://reactjs.org/docs/hooks-reference.html#usecallback) for memoization.
  Arrays and objects are automatically memoized.
</Note>

<ParamField body="escapeHTML" type="boolean" default={true}>
  Whether to escape HTML tags from hits string values.

  ```jsx JavaScript icon=code theme={"system"}
  const hitsApi = useHits({
    escapeHTML: false,
  });
  ```
</ParamField>

<ParamField body="transformItems" type="(items: object[], metadata: { results: SearchResults }) => object[]" 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/react) widget,
  you must also transform the corresponding `item._highlightResult[attribute].value`.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    // Using only items
    const transformItems = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems = (items, { results }) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function Hits() {
      const hitsApi = useHits({
        // ...
        transformItems,
      });

      return <>{/* Your JSX */}</>;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { UseHitsProps } from 'react-instantsearch';

    // Using only items
    const transformItems: UseHitsProps['transformItems'] = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems: UseHitsProps['transformItems'] = (items, { results }) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function Hits() {
      const hitsApi = useHits({
        // ...
        transformItems,
      });

      return <>{/* Your JSX */}</>;
    }
    ```
  </CodeGroup>
</ParamField>

### APIs

Hooks return APIs, such as state and functions. You can use them to build your UI and interact with React InstantSearch.

<ResponseField name="items" type="THit[]">
  The matched items returned from Algolia.

  You can use [Algolia's highlighting feature](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#highlight-and-snippet-your-search-results) directly from the render function.
</ResponseField>

<ResponseField name="results" type="SearchResults<THit>">
  The complete response from Algolia.

  It contains the `hits` but also metadata about the page, number of hits, and more.
  Unless you need to access metadata, use [`items`](#param-items) instead.
</ResponseField>

<ResponseField name="banner" type="SearchResults<THit>['renderingContent']['widgets']['banners'][0]">
  The banner data on the `renderingContent` property from the Algolia response.
</ResponseField>

<ResponseField name="sendEvent" type="(eventType: string, hits: Hit  |  Hits, eventName?: string) => void">
  The function to send `click` or `conversion` events.

  The `view` event is automatically sent when this Hook renders hits.
  Check the [`insights`](/doc/api-reference/widgets/insights/js) documentation to learn more.
</ResponseField>

### Example

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React from 'react';
  import { useHits } from 'react-instantsearch';

  function CustomHits(props) {
    const { items, sendEvent } = useHits(props);

    return (
      <ol>
        {items.map((hit) => (
          <li
            key={hit.objectID}
            onClick={() => sendEvent('click', hit, 'Hit Clicked')}
            onAuxClick={() => sendEvent('click', hit, 'Hit Clicked')}
          >
            <div style={{ wordBreak: 'break-all' }}>
              {JSON.stringify(hit).slice(0, 100)}
            </div>
          </li>
        ))}
      </ol>
    );
  }

  ```

  ```tsx TypeScript theme={"system"}
  import React from 'react';
  import {
    useHits,
    UseHitsProps,
  } from 'react-instantsearch';

  function CustomHits(props: UseHitsProps) {
    const { items, sendEvent } = useHits(props);

    return (
      <ol>
        {items.map((hit) => (
          <li
            key={hit.objectID}
            onClick={() => sendEvent('click', hit, 'Hit Clicked')}
            onAuxClick={() => sendEvent('click', hit, 'Hit Clicked')}
          >
            <div style={{ wordBreak: 'break-all' }}>
              {JSON.stringify(hit).slice(0, 100)}
            </div>
          </li>
        ))}
      </ol>
    );
  }
  ```
</CodeGroup>

## Click and conversion events

If the [`insights`](/doc/api-reference/widgets/instantsearch/react#param-insights) option is `true`, the `Hits` component 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 [`hitComponent`](/doc/api-reference/widgets/hits/react#param-hit-component) and send a custom `click` event.

```jsx JavaScript icon=code theme={"system"}
<Hits
  hitComponent={({ hit, sendEvent }) => (
    <div onClick={() => sendEvent("click", hit, "Product Clicked")}>
      <h2>
        <Highlight attributeName="name" hit={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.

```jsx JavaScript icon=code theme={"system"}
<Hits
  hitComponent={({ hit, sendEvent }) => (
    <div>
      <h2>
        <Highlight attributeName="name" hit={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 React InstantSearch](/doc/guides/building-search-ui/events/react)
