🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / React InstantSearch / Widgets

This is the React InstantSearch v7 documentation. React InstantSearch v7 is the latest version of React InstantSearch and the stable version of React InstantSearch Hooks.

If you were using React InstantSearch v6, you can upgrade to v7.

If you were using React InstantSearch Hooks, you can still use the React InstantSearch v7 documentation, but you should check the upgrade guide for necessary changes.

If you want to keep using React InstantSearch v6, you can find the archived documentation.

Signature
<InfiniteHits
  // Optional props
  hitComponent={({ hit }) => JSX.Element}
  showPrevious={boolean}
  transformItems={function}
  cache={object}
  classNames={object}
  translations={object}
  ...props={ComponentProps<'div'>}
/>
Import
1
import { InfiniteHits } from 'react-instantsearch';

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 describes how to create an automatically-scrolling infinite hits experience.

If there are no hits, you should display a message to users and clear filters so they can start over.

You can also create your own UI with useInfiniteHits().

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, InfiniteHits } from 'react-instantsearch';

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

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

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

Props

Parameter Description
hitComponent
type: (props: { hit: THit; sendEvent: SendEventForHits }) => JSX.Element
Required

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.

1
<InfiniteHits hitComponent={({ hit }) => hit.objectID} />
showPrevious
type: boolean
default: true
Optional

Enable the button to load previous results.

1
2
3
4
<InfiniteHits
  // ...
  showPrevious={false}
/>
escapeHTML
type: boolean
default: true
Optional

Whether to escape HTML tags from hits string values.

1
2
3
4
<InfiniteHits
  // ...
  escapeHTML={false}
/>
transformItems
type: (items: object[], metadata: { results: SearchResults }) => object[]
Optional

Receives the items and is called before displaying them. It returns a new array with the same “shape” as the original. This is helpful when transforming, removing, or reordering items.

The complete results data is also available, including all regular response parameters and helper parameters (for example, disjunctiveFacetsRefinements).

If you’re transforming an attribute with the <Highlight> widget, you must transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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 (
    <InfiniteHits
      // ...
      transformItems={transformItems}
    />
  );
}
cache
type: InfiniteHitsCache
Optional

The widget caches all loaded hits. By default, it uses its own internal in-memory cache implementation. Alternatively, use sessionStorage to retain the cache even if users reload the page.

You can also implement your own cache object with read and write methods.

1
2
3
4
5
6
7
8
import { createInfiniteHitsSessionStorageCache } from 'instantsearch.js/es/lib/infiniteHitsCache';

const sessionStorageCache = createInfiniteHitsSessionStorageCache();

<InfiniteHits
  // ...
  cache={sessionStorageCache}
/>
classNames
type: Partial<InfiniteHitsClassNames>
Optional

CSS classes to pass to the widget’s elements. This helps when styling 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 items.
  • loadPrevious: the “Load previous” button.
  • disabledLoadPrevious: the “Load previous” button when there are no previous results to load.
  • loadMore: the “Load more” button.
  • disabledLoadMore: the “Load more” button when there are no more results to load.
1
2
3
4
5
6
7
<InfiniteHits
  // ...
  classNames={{
    root: 'MyCustomInfiniteHits',
    list: 'MyCustomInfiniteHitsList MyCustomInfiniteHitsList--subclass',
  }}
/>
translations
type: Partial<InfiniteHitsTranslations>
Optional

A dictionary of translations to customize the UI text and support internationalization.

  • showPreviousButtonText: The text for the “Show previous” button.
  • showMoreButtonText: The text for the “Show more” button.
1
2
3
4
5
6
7
<InfiniteHits
  // ...
  translations={{
    showPreviousButtonText: 'Load previous results',
    showMoreButtonText: 'Load more results',
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

Any <div> prop to forward to the widget’s root element.

1
2
3
4
5
<InfiniteHits
  // ...
  className="MyCustomInfiniteHits"
  title="My custom title"
/>

Hook

React InstantSearch let you create your own UI for the <InfiniteHits> widget with useInfiniteHits(). Hooks provide APIs to access the widget state and interact with InstantSearch.

The useInfiniteHits() Hook accepts parameters and returns APIs.

Usage

First, create your React component:

import { useInfiniteHits } from 'react-instantsearch';

function CustomInfiniteHits(props) {
  const {
    hits,
    currentPageHits,
    results,
    isFirstPage,
    isLastPage,
    showPrevious,
    showMore,
    sendEvent,
  } = useInfiniteHits(props);

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

Then, render the widget:

<CustomInfiniteHits {...props} />

Parameters

Hooks accept parameters. You can pass them manually, or forward the props from your custom component.

When you provide a function to Hooks, make sure to pass a stable reference to avoid rendering endlessly (for example, with useCallback()). Objects and arrays are memoized; you don’t need to stabilize them.

Parameter Description
escapeHTML
type: boolean
default: true

Whether to escape HTML tags from hits string values.

1
2
3
const infiniteHitsApi = useInfiniteHits({
  escapeHTML: false,
});
transformItems
type: (items: object[], metadata: { results: SearchResults }) => object[]

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

The complete results data is also available, including all regular response parameters and helper parameters (for example, disjunctiveFacetsRefinements).

If you’re transforming an attribute with the <Highlight> widget, you must transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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 InfiniteHits() {
  const infiniteHitsApi = useInfiniteHits({
    // ...
    transformItems,
  });

  return <>{/* Your JSX */}</>;
}
cache
type: InfiniteHitsCache

The Hook internally caches all loaded hits using its own internal in-memory cache implementation.

The library provides another implementation using sessionStorage, which is more persistent and lets you restore the scroll position when you leave and come back to the search page.

You can also provide your own implementation by providing a cache object with read and write methods.

1
2
3
4
5
6
7
import { createInfiniteHitsSessionStorageCache } from 'instantsearch.js/es/lib/infiniteHitsCache';

const sessionStorageCache = createInfiniteHitsSessionStorageCache();

const infiniteHitsApi = useInfiniteHits({
  cache: sessionStorageCache,
});

APIs

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

Parameter Description
hits
type: THit[]

The matched hits returned from Algolia.

This returns the combined hits for all the pages that have been requested so far. Use Algolia’s highlighting feature directly from the render function.

currentPageHits
type: THit[]

The matched hits from Algolia for the current page.

Unlike the hits parameter, this only returns the hits for the requested page. This can be useful if you want to customize how to add the new page of hits to the existing list.

You can use Algolia’s highlighting feature directly from the render function.

results
type: SearchResults<THit>

The complete response from Algolia.

It contains the hits, metadata about the page, the number of hits, and more. Unless you need to access metadata, use hits instead.

isFirstPage
type: boolean

Whether the first page of hits has been reached.

isLastPage
type: boolean

Whether the last page of hits has been reached.

showPrevious
type: () => void

Loads the previous page of hits.

showMore
type: () => void

Loads the next page of hits.

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 documentation to learn more.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React from 'react';
import { useInfiniteHits } from 'react-instantsearch';

function CustomInfiniteHits(props) {
  const { hits, sendEvent, showPrevious, showMore, isFirstPage, isLastPage } =
    useInfiniteHits(props);

  return (
    <div>
      <button onClick={showPrevious} disabled={isFirstPage}>
        Show previous results
      </button>
      <ol>
        {hits.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>
      <button onClick={showMore} disabled={isLastPage}>
        Show more results
      </button>
    </div>
  );
}

Click and conversion events

If the insights option is true, the InfiniteHits component automatically sends a click event with the following “shape” to the Insights API whenever the user clicks on a hit.

1
2
3
4
5
6
7
8
9
{
  eventType: 'click',
  insightsMethod: 'clickedObjectIDsAfterSearch',
  payload: {
    eventName: 'Hit Clicked',
    // 
  },
  widgetType: 'ais.infiniteHits',
}

To customize this event, use the sendEvent function in your hitComponent and send a custom click event.

1
2
3
4
5
6
7
8
9
10
<InfiniteHits
  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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<InfiniteHits
  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 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>
  )}
/>

Fields representing monetary values accept both numbers and strings, in major currency units (for example, 5.45 or '5.45'). To prevent floating-point math issues, use strings, especially if you’re performing calculations.

Did you find this page helpful?