🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / InstantSearch.js / Widgets
Signature
infiniteHits({
  container: string|HTMLElement,
  // Optional parameters
  escapeHTML: boolean,
  showPrevious: boolean,
  templates: object,
  cssClasses: object,
  transformItems: function,
  cache: object,
});
Import
1
import { infiniteHits } from 'instantsearch.js/es/widgets';

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.

To configure the number of hits to show, use the hitsPerPage widget or the configure widget.

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

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
infiniteHits({
  container: '#infinite-hits',
  templates: {
    item(hit, { html, components }) {
      return html`
        <h2>
          ${components.Highlight({ attribute: 'name', hit })}
        </h2>
        <p>${hit.description}</p>
      `;
    },
  },
});

Options

Parameter Description
container
type: string|HTMLElement
Required

The CSS Selector or HTMLElement to insert the widget into.

1
2
3
infiniteHits({
  container: '#infinite-hits',
});
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from hits string values.

1
2
3
4
infiniteHits({
  // ...
  escapeHTML: false,
});
showPrevious
type: boolean
default: false
Optional

Enable the button to load previous results.

The button is only displayed if the routing option is enabled in instantsearch and the user isn’t on the first page. Override this behavior with connectors.

1
2
3
4
infiniteHits({
  // ...
  showPrevious: true,
});
templates
type: object
Optional

The templates to use for the widget.

1
2
3
4
5
6
infiniteHits({
  // ...
  templates: {
    // ...
  },
});
cssClasses
type: object
default: {}
Optional

The CSS classes you can override:

  • 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.
1
2
3
4
5
6
7
8
9
10
infiniteHits({
  // ...
  cssClasses: {
    root: 'MyCustomInfiniteHits',
    list: [
      'MyCustomInfiniteHits',
      'MyCustomInfiniteHits--subclass',
    ],
  },
});
transformItems
type: function
default: items => items
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
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 },
    }));
  },
});
cache
type: object
default: in-memory cache object
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
const sessionStorageCache =
  instantsearch.createInfiniteHitsSessionStorageCache();

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

Templates

You can customize parts of the widget’s UI using the Templates API.

Every template provides an html function you can use as a tagged template. Using html lets you safely provide templates as an HTML string. It works directly in the browser without a build step. See Templating your UI for more information.

The html function is available starting from v4.46.0.

Parameter Description
empty
type: string|function
Optional

The template to use when there are no results. It exposes the results object.

1
2
3
4
5
6
7
8
infiniteHits({
  // ...
  templates: {
    empty(results, { html }) {
      return html`<p>No results <q>${results.query}</q></p>`;
    },
  },
});
item
type: string|function
Optional

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 with the highlight function, directly from the template.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
infiniteHits({
  // ...
  templates: {
    item(hit, { html, components }) {
      return html`
        <h2>
          ${hit.__hitIndex}:
          ${components.Highlight({ attribute: 'name', hit })}
        </h2>
        <p>${hit.description}</p>
      `;
    },
  },
});
showPreviousText
type: string|function
default: Show previous results
Optional

The template to use for the “Show previous” label.

1
2
3
4
5
6
7
8
infiniteHits({
  // ...
  templates: {
    showPreviousText(data, { html }) {
      return html`<span>Show previous</span>`;
    },
  },
});
showMoreText
type: string|function
default: Show more results
Optional

The template to use for the “Show more” label.

1
2
3
4
5
6
7
8
infiniteHits({
  // ...
  templates: {
    showMoreText(data, { html }) {
      return html`<span>Show more</span>`;
    },
  },
});

HTML output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div class="ais-InfiniteHits">
  <button class="ais-InfiniteHits-loadPrevious">
    Show previous
  </button>
  <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.

1
import { connectInfiniteHits } from 'instantsearch.js/es/connectors';

Then it’s a 3-step process:

// 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).

const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const {
    object[] hits,
    object[] currentPageHits,
    object results,
    function sendEvent,
    boolean isFirstPage,
    boolean isLastPage,
    function showPrevious,
    function showMore,
    object widgetParams,
  } = renderOptions;

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

  // Render the widget
}

Rendering options

Parameter Description
hits
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 with the highlight function, directly from the connector’s render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const { hits } = renderOptions;

  document.querySelector('#infinite-hits').innerHTML = `
    <ul>
      ${hits
        .map(
          item =>
            `<li>
              ${instantsearch.highlight({ attribute: 'name', hit: item })}
            </li>`
        )
        .join('')}
    </ul>
  `;
};
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 with the highlight function, directly from the connector’s render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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(''));
};
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 hits instead. You should also consider the stats widget if you want to build a widget that displays metadata about the search.

1
2
3
4
5
6
7
8
9
10
11
12
13
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>
  `;
};
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

Learn more about these events in the insights middleware documentation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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',
  }
*/
isFirstPage
type: boolean

Indicates whether the first page of hits has been reached.

1
2
3
4
5
6
7
8
9
10
11
12
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const { hits, isFirstPage } = renderOptions;

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

Indicates whether the last page of hits has been reached.

1
2
3
4
5
6
7
8
9
10
11
12
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const { hits, isLastPage } = renderOptions;

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

Loads the previous page of hits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const { hits, 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 = `
    ${hits.map(item => `<li>${item.name}</li>`).join('')}
  `;
};
showMore
type: function

Loads the next page of hits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const { hits, 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 = `
    ${hits.map(item => `<li>${item.name}</li>`).join('')}
  `;
};
widgetParams
type: object

All original widget options forwarded to the render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

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

// ...

search.addWidgets([
  customInfiniteHits({
    container: document.querySelector('#infinite-hits'),
  })
]);

Create and instantiate the custom widget

We first create custom widgets from our rendering function, then we instantiate them. When doing that, there are two types of parameters you can give:

  • Instance parameters: they are predefined parameters that you can use to configure the behavior of Algolia.
  • Your own parameters: to make the custom widget generic.

Both instance and custom parameters are available in connector.widgetParams, inside the renderFunction.

const customInfiniteHits = connectInfiniteHits(
  renderInfiniteHits
);

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

Instance options

Parameter Description
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from hits string values.

1
2
3
customInfiniteHits({
  escapeHTML: false,
});
showPrevious
type: boolean
default: false
Optional

Enable the button to load previous results.

1
2
3
customInfiniteHits({
  showPrevious: true,
});
transformItems
type: function
default: items => items
Optional

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

The entire 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
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 },
    }));
  },
});

Full 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Create the render function
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  const {
    hits,
    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 = `
    ${hits
      .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,
  })
]);

Click and conversion events

If the 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.

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 item template and send a custom click event.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.

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
36
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>
      `;
    },
  },
});

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?