API Reference / InstantSearch.js Widgets / infiniteHits
Aug. 23, 2019

infiniteHits

Widget signature
instantsearch.widgets.infiniteHits({
  container: string|HTMLElement,
  // Optional parameters
  escapeHTML: boolean,
  showPrevious: boolean,
  templates: object,
  cssClasses: object,
  transformItems: function,
});

About this widget

The infiniteHits widget is used to display a list of results with a “Show more” button.

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

Examples

1
2
3
4
5
6
7
8
9
10
11
instantsearch.widgets.infiniteHits({
  container: '#infinite-hits',
  templates: {
    item: `
      <h2>
        {{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}
      </h2>
      <p>{{ description }}</p>
    `,
  },
});

Options

container
type: string|HTMLElement
Required

The CSS Selector or HTMLElement to insert the widget into.

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

Escapes HTML entities from hits string values.

1
2
3
4
instantsearch.widgets.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 if the user is not on the first page. It’s possible to override this behavior by using connectors.

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

The templates to use for the widget.

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

The CSS classes to override.

  • root: the root element of the widget.
  • 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
instantsearch.widgets.infiniteHits({
  // ...
  cssClasses: {
    root: 'MyCustomInfiniteHits',
    list: [
      'MyCustomInfiniteHits',
      'MyCustomInfiniteHits--subclass',
    ],
  },
});
transformItems
type: function
default: x => x
Optional

Receives the items, and is called before displaying them. Should return a new array with the same shape as the original array. Useful for mapping over the items to transform, and remove or reorder them.

1
2
3
4
5
6
7
8
9
instantsearch.widgets.infiniteHits({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Templates

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
instantsearch.widgets.infinteHits({
  // ...
  templates: {
    empty: 'No results for <q>{{ query }}</q>',
  },
});
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 leverage the highlighting feature of Algolia through the highlight function, directly from the template.

1
2
3
4
5
6
7
8
9
10
11
12
instantsearch.widgets.infiniteHits({
  // ...
  templates: {
    item: `
      <h2>
        {{ __hitIndex }}:
        {{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}
      </h2>
      <p>{{ 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
instantsearch.widgets.infiniteHits({
  // ...
  templates: {
    showPreviousText: 'Show previous',
  },
});
showMoreText
type: string|function
default: Show more results
Optional

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

1
2
3
4
5
6
instantsearch.widgets.infiniteHits({
  // ...
  templates: {
    showMoreText: 'Show more',
  },
});

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 - connectInfiniteHits

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

It’s a 3-step process:

// 1. Create a render function
const renderInfiniteHits = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customInfiniteHits = instantsearch.connectors.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 results,
    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

hits
type: object[]

The matched hits from the Algolia API. You can leverage the highlighting feature of Algolia through 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>
  `;
};
results
type: object

The complete response from the Algolia API. It contains the hits but also metadata about the page, number of hits, etc. We recommend using hits rather than this option. You can also take a look at 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>
  `;
};
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 = instantsearch.connectors.connectInfiniteHits(
  renderInfiniteHits
);

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

Instance options

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: x => x
Optional

Receives the items, and is called before displaying them. Should return a new array with the same shape as the original array. Useful for mapping over the items to transform, and remove or reorder them.

1
2
3
4
5
6
7
8
customInfiniteHits({
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

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 = instantsearch.connectors.connectInfiniteHits(
  renderInfiniteHits
);

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

Sending Click and Conversion events

InstantSearch can connect with the insights Javascript Client to allow sending click and conversion events right from the infiniteHits widget.

Requirements

This requires installing the search-insights library separately:

You can refer to our insights documentation for more details.

It’s a 3-step process:

1. Install the Insights API client for JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@1.3.0";

  !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e.aa=e.aa||function(){
  (e.aa.queue=e.aa.queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],
  i.async=1,i.src=ALGOLIA_INSIGHTS_SRC,c.parentNode.insertBefore(i,c)
  }(window,document,"script",0,"aa");

  aa('init', {
    appId: 'YourApplicationID',
    apiKey: 'YourSearchOnlyAPIKey',
  });
</script>

2. Connect the Insights API client for JavaScript with InstantSearch and enable clickAnalytics

1
2
3
4
5
6
7
8
9
10
const search = instantsearch({
  // ...
  insightsClient: window.aa
});

search.addWidgets([
   instantsearch.widgets.configure({
     clickAnalytics: true,
   })
]);

3. Call the insights function from your infiniteHits component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
search.addWidgets([
  instantsearch.widgets.infinitehits({
    // ...
    templates: {
      item(hit) {
        return `
          <a href="/product.html?queryID=${hit.__queryID}">
            <h2>${hit.name}</h2>
            <button ${
              instantsearch.insights('clickedObjectIDsAfterSearch', {
                eventName: 'Add to favorite',
                objectIDs: [hit.objectID]
              })
            }>
              Add to favorite
            </button>
          </a>
        `;
      },
    },
  })
]);

Provided props

insights
type: function
signature: (method: string, payload: object) => void

Sends insights events.

  • method: string: the insights method to be called. Only search-related methods are supported: 'clickedObjectIDsAfterSearch', 'convertedObjectIDsAfterSearch'.

  • payload: object: the payload to be sent.

    • eventName: string: the name of the event.
    • objectIDs: string[]: a list of objectIDs.
    • index?: string: the name of the index related to the click.
    • queryID?: string: the Algolia queryID that can be found in the search response when using clickAnalytics: true.
    • userToken?: string: a user identifier.
    • positions?: number[]: the position of the click in the list of Algolia search results.

When not provided, index, queryID, and positions are inferred by the InstantSearch context and the passed objectIDs:

  • index by default is the name of index that returned the hits.
  • queryID by default is the ID of the query that returned the hits.
  • positions by default is the absolute positions of the hits selected with the passed objectIDs.

It is worth noting that hit has the following read-only properties:

  • __queryID: the query ID (only if clickAnalytics is set to true).
  • __position: the absolute position of the hit.

For more details on the constraints that apply to each payload property, please refer to the insights client documentation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
instantsearch.widgets.infiniteHits({
  // ...
  templates: {
    item(hit) {
      return `
        <h2>${hit.name}</h2>
        <button ${
          instantsearch.insights('clickedObjectIDsAfterSearch', {
            eventName: 'Add to favorite',
            objectIDs: [hit.objectID]
          })
        }>
          Add to favorite
        </button>
      `;
    },
  },
});

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
search.addWidgets([
  instantsearch.widgets.infiniteHits({
    // ...
    templates: {
      item(hit) {
        return `
          <div>
            <a href="/product.html?queryID=${hit.__queryID}">
              <h2>${hit.name}</h2>
            </a>
            <button ${
              instantsearch.insights('clickedObjectIDsAfterSearch', {
                eventName: 'Add to favorite',
                objectIDs: [hit.objectID]
              })
            }>
              Add to favorite
            </button>
          </div>
        `;
      },
    },
  })
]);

Did you find this page helpful?