Concepts / Building Search UI / Infinite scroll
Sep. 13, 2019

Infinite Scroll

Overview

The infinite list is a very common pattern to display a list of results. Most of the times this pattern comes with two variants:

  • with a button to click on at the end of the list of results
  • with a listener on the scroll event that is called when the list of results reaches the end

We can cover those two different implementations with InstantSearch.js. The former is covered by the built-in infiniteHits widget and the latter is covered by the infiniteHits connector. In this guide we will focus on the second implementation using the Intersection Observer API. We choose to use a browser API in the example but the concepts can be applied to any kind of infinite scroll library. You can find the complete example on GitHub.

Note that the Intersection Observer API isn’t yet widely supported. You may want to consider using a polyfill. Here the compatibility table to find more information about its support.

Display a list of hits

The first step to create our infinite scroll widget is to render the results with the infiniteHits connector. You can find more information about the connectors in the dedicated guide.

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
const infiniteHits = instantsearch.connectors.connectInfiniteHits(
  (renderArgs, isFirstRender) => {
    const { hits, showMore, widgetParams } = renderArgs;
    const { container } = widgetParams;

    if (isFirstRender) {
      container.appendChild(document.createElement('ul'));

      return;
    }

    container.querySelector('ul').innerHTML = hits
      .map(
        hit =>
          `<li>
            <div class="ais-Hits-item">
              <header class="hit-name">
                ${instantsearch.highlight({ attribute: 'name', hit })}
              </header>
              <img src="${hit.image}" align="left" />
              <p class="hit-description">
                ${instantsearch.highlight({ attribute: 'description', hit })}
              </p>
              <p class="hit-price">$${hit.price}</p>
            </div>
          </li>`
      )
      .join('');
  }
);

Track the scroll position

We have our list of results, the next step is to track the scroll position to determine when the rest of the content needs to be loaded. For this purpose we are gonna use the Intersection Observer API. To track when the bottom of the list enters inside the viewport we observe a “sentinel” element. We use this trick to avoid observing all the items of our results. We can reuse the same element across different renders. You can find more information about this pattern on the Web Fundamentals website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const infiniteHits = instantsearch.connectors.connectInfiniteHits(
  (renderArgs, isFirstRender) => {
    const { hits, showMore, widgetParams } = renderArgs;
    const { container } = widgetParams;

    if (isFirstRender) {
      const sentinel = document.createElement('div');
      container.appendChild(document.createElement('ul'));
      container.appendChild(sentinel);

      return;
    }

    // ...
  }
);

Once we have the reference to our “sentinel” element we can create the Intersection Observer instance to observe when this element enter or not inside the page. You can provide options to the Intersection Observer API don’t hesitate to adjust the example to your needs.

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
const infiniteHits = instantsearch.connectors.connectInfiniteHits(
  (renderArgs, isFirstRender) => {
    const { hits, showMore, widgetParams } = renderArgs;
    const { container } = widgetParams;

    if (isFirstRender) {
      const sentinel = document.createElement('div');
      container.appendChild(document.createElement('ul'));
      container.appendChild(sentinel);

      const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            // In that case we can refine
          }
        });
      });

      observer.observe(sentinel);

      return;
    }

    // ...
  }
);

Retrieve more results

Now that we are able to track when we reach the end of our results we can hook the showMore function inside the callback function of the observer. But we should only trigger the function when we still have results to retrieve. For this use case the connector provide a parameter isLastPage that indicates if we still have results or not.

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
let lastRenderArgs;

const infiniteHits = instantsearch.connectors.connectInfiniteHits(
  (renderArgs, isFirstRender) => {
    const { hits, showMore, widgetParams } = renderArgs;
    const { container } = widgetParams;

    lastRenderArgs = renderArgs;

    if (isFirstRender) {
      const sentinel = document.createElement('div');
      container.appendChild(document.createElement('ul'));
      container.appendChild(sentinel);

      const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
          if (entry.isIntersecting && !lastRenderArgs.isLastPage) {
            showMore();
          }
        });
      });

      observer.observe(sentinel);

      return;
    }

    // ...
  }
);

Go further than 1000 hits

By default Algolia limits the number of hits you can retrieve for a query to 1000; when doing an infinite scroll, you usually don’t want to go over this limit.

1
2
3
$index->setSettings([
  'paginationLimitedTo' => 1000
]);

Disabling the limit does not mean that we will be able to go until the end of the hits, but just that Algolia will go as far as possible in the index to retrieve results in a reasonable time.

That’s it! Now you should have a complete infinite scroll experience! Don’t forget that the complete source code of the example is available on GitHub.

Did you find this page helpful?