Skip to main content
This is the React InstantSearch v7 documentation. If you’re upgrading from v6, see the upgrade guide. If you were using React InstantSearch Hooks, this v7 documentation applies—just check for necessary changes. To continue using v6, you can find the archived documentation.
Signature
<Hits
  // Optional props
  hitComponent={({ hit }) => JSX.Element}
  classNames={object}
  ...props={ComponentProps<'div'>}
/>

Import

JavaScript
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> widget or pass the hitsPerPage prop to the <Configure> widget. See also:
You can also create your own UI with useHits.

Examples

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

Props

hitComponent
(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) prop.When not provided, the widget displays the hit as a JSON string.
JavaScript
<Hits hitComponent={({ hit }) => hit.objectID} />;
bannerComponent
((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.
JavaScript
// Override the default banner rendering
<Hits
  // ...
  bannerComponent={({ banner }) => <img src={banner.image.urls[0].url} />}
/>

// Disable the banner rendering

<Hits
  // ...
  bannerComponent={false}
/>
escapeHTML
boolean
default:true
Whether to escape HTML tags from hits string values.
JavaScript
<Hits
  // ...
  escapeHTML={false}
/>;
transformItems
(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 and parameters from the helper, such as disjunctiveFacetsRefinements.If you transform an attribute used in the <Highlight> widget, you must also transform the corresponding item._highlightResult[attribute].value.
// 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}
    />
  );
}
classNames
Partial<HitsClassNames>
The CSS classes you can override and pass to the widget’s elements. It’s useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.
  • 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.
JavaScript
<Hits
  // ...
  classNames={{
    root: "MyCustomHits",
    list: "MyCustomHitsList MyCustomHitsList--subclass",
  }}
/>;
...props
React.ComponentProps<'div'>
Any <div> prop to forward to the widget’s root element.
JavaScript
<Hits className="MyCustomHits" title="My custom title" />;

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 and returns APIs. It must be used inside the <InstantSearch> component.

Usage

First, create your React component:
JavaScript
import { useHits } from "react-instantsearch";

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

  return <>{/*Your JSX*/}</>;
}
Then, render the widget:
JavaScript
<CustomHits {...props} />;

Parameters

Hooks accept parameters. You can either pass them manually or forward props from a custom component.
When passing functions to Hooks, ensure stable references to prevent unnecessary re-renders. Use useCallback() for memoization. Arrays and objects are automatically memoized.
escapeHTML
boolean
default:true
Whether to escape HTML tags from hits string values.
JavaScript
const hitsApi = useHits({
  escapeHTML: false,
});
transformItems
(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 and parameters from the helper, such as disjunctiveFacetsRefinements.If you transform an attribute used in the <Highlight> widget, you must also transform the corresponding item._highlightResult[attribute].value.
// 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 */}</>;
}

APIs

Hooks return APIs, such as state and functions. You can use them to build your UI and interact with React InstantSearch.
items
THit[]
The matched items returned from Algolia.You can use Algolia’s highlighting feature directly from the render function.
results
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 instead.
banner
SearchResults<THit>['renderingContent']['widgets']['banners'][0]
The banner data on the renderingContent property from the Algolia response.
sendEvent
(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 documentation to learn more.

Example

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

Click and conversion events

If the 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.
JSON
{
  "eventType": "click",
  "insightsMethod": "clickedObjectIDsAfterSearch",
  "payload": {
    "eventName": "Hit Clicked"
    // …
  },
  "widgetType": "ais.hits"
}
To customize this event, use the sendEvent function in your hitComponent and send a custom click event.
JavaScript
<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.
JavaScript
<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>
  )}
/>
Use strings to represent monetary values in major currency units (for example, ‘5.45’). This avoids floating-point rounding issues, especially when performing calculations.
See also: Send click and conversion events with React InstantSearch
I