> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# pagination

> Adds controls for navigating search result pages.

<div className="not-prose algolia-flavor-switcher">
  <div className="afs-dropdown">
    <div className="afs-trigger" role="button" tabIndex="0" aria-haspopup="listbox">
      <span className="afs-current">JavaScript</span>

      <svg className="afs-chevron lucide lucide-chevron-down" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>

    <ul className="afs-menu" role="listbox">
      <li role="option" aria-selected="true"><a className="afs-option is-current" href="/doc/api-reference/widgets/pagination/js"><span className="afs-option-name">JavaScript</span><span className="afs-option-lib">InstantSearch.js</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/pagination/react"><span className="afs-option-name">React</span><span className="afs-option-lib">React InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/pagination/vue"><span className="afs-option-name">Vue</span><span className="afs-option-lib">Vue InstantSearch</span></a></li>
    </ul>
  </div>
</div>

```ts Signature theme={"system"}
pagination({
  container: string | HTMLElement,
  // Optional parameters
  showFirst: boolean,
  showPrevious: boolean,
  showNext: boolean,
  showLast: boolean,
  padding: number,
  totalPages: number,
  scrollTo: string | HTMLElement | boolean,
  templates: object,
  cssClasses: object,
});
```

<CodeGroup>
  ```js Package manager theme={"system"}
  import { pagination } from 'instantsearch.js/es/widgets';
  ```

  ```js CDN theme={"system"}
  const { pagination } = instantsearch.widgets;
  // or directly use instantsearch.widgets.pagination()
  ```
</CodeGroup>

[See live example]()

<Card title="See this widget in action" icon="monitor-play" href="https://instantsearchjs.netlify.app/stories/js/?path=/story/pagination-pagination--default" horizontal>
  Preview this widget and its behavior.
</Card>

## About this widget

The `pagination` widget displays a pagination system which lets users change the current page of search results.

<Info>
  Pagination is limited to 1,000 hits per page.
  For more information, see [Pagination limitations](/doc/guides/building-search-ui/ui-and-ux-patterns/pagination/js#pagination-limitations).
</Info>

## Examples

```js JavaScript icon=code theme={"system"}
pagination({
  container: "#pagination",
});
```

## Options

<ParamField body="container" type="string | HTMLElement" required>
  The CSS Selector or `HTMLElement` to insert the widget into.

  <CodeGroup>
    ```js string theme={"system"}
    pagination({
      container: '#pagination',
    });
    ```

    ```js HTMLElement theme={"system"}
    pagination({
      container: document.querySelector("#pagination"),
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="showFirst" type="boolean" default={true}>
  Whether to display the first page link.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    showFirst: false,
  });
  ```
</ParamField>

<ParamField body="showPrevious" type="boolean" default={true}>
  Whether to display the previous page link.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    showPrevious: false,
  });
  ```
</ParamField>

<ParamField body="showNext" type="boolean" default={true}>
  Whether to display the next page link.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    showNext: false,
  });
  ```
</ParamField>

<ParamField body="showLast" type="boolean" default={true}>
  Whether to display the last page link.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    showLast: false,
  });
  ```
</ParamField>

<ParamField body="padding" type="number" default={3}>
  The number of pages to display on each side of the current page.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    padding: 2,
  });
  ```
</ParamField>

<ParamField body="totalPages" type="number">
  The maximum number of pages to browse.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    totalPages: 2,
  });
  ```
</ParamField>

<ParamField body="scrollTo" type="string | HTMLElement | boolean" default="body">
  Where to scroll after a click. Set to `false` to disable.

  <CodeGroup>
    ```js string theme={"system"}
    pagination({
      // ...
      scrollTo: 'header',
    });
    ```

    ```js HTMLElement theme={"system"}
    pagination({
      // ...
      scrollTo: document.querySelector(".header"),
    });
    ```

    ```js boolean theme={"system"}
    pagination({
      // ...
      scrollTo: false,
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="templates" type="object">
  The [templates](#templates) to use for the widget.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    templates: {
      // ...
    },
  });
  ```
</ParamField>

<ParamField body="cssClasses" type="object" default="{}">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#style-your-widgets):

  * `root`. The root element of the widget.
  * `noRefinementRoot`. The root container without results.
  * `list`. The list of results.
  * `item`. The item in the list of results.
  * `firstPageItem`. The first item.
  * `lastPageItem`. The last item.
  * `previousPageItem`. The previous item.
  * `nextPageItem`. The next item.
  * `pageItem`. The page items.
  * `selectedItem`. The selected item.
  * `disabledItem`. The disabled item.
  * `link`. The link elements.

  ```js JavaScript icon=code theme={"system"}
  pagination({
    // ...
    cssClasses: {
      root: "MyCustomPagination",
      list: ["MyCustomPaginationList", "MyCustomPaginationList--subclass"],
    },
  });
  ```
</ParamField>

## Templates

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

Each template includes an `html` function,
which you can use as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).
This function safely renders templates as HTML strings and works directly in the browser—no build step required.
For details, see [Templating your UI](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js/#templating-your-ui).

<Note>
  The `html` function is available in InstantSearch.js version 4.46.0 or later.
</Note>

<ParamField body="first" type="string | function">
  The template for the first page.

  <CodeGroup>
    ```js string theme={"system"}
    pagination({
      // ...
      templates: {
        first: '«',
      },
    });
    ```

    ```js function theme={"system"}
    pagination({
      // ...
      templates: {
        first() {
          return "«";
        },
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="previous" type="string | function">
  The template for the previous page.

  <CodeGroup>
    ```js string theme={"system"}
    pagination({
      // ...
      templates: {
        previous: '‹',
      },
    });
    ```

    ```js function theme={"system"}
    pagination({
      // ...
      templates: {
        previous() {
          return "‹";
        },
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="next" type="string | function">
  The template for the next page.

  <CodeGroup>
    ```js string theme={"system"}
    pagination({
      // ...
      templates: {
        next: '›',
      },
    });
    ```

    ```js function theme={"system"}
    pagination({
      // ...
      templates: {
        next() {
          return "›";
        },
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="last" type="string | function">
  The template for the last page.

  <CodeGroup>
    ```js string theme={"system"}
    pagination({
      // ...
      templates: {
        last: '»',
      },
    });
    ```

    ```js function theme={"system"}
    pagination({
      // ...
      templates: {
        last() {
          return "»";
        },
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<div class="ais-Pagination">
  <ul class="ais-Pagination-list">
    <li
      class="ais-Pagination-item ais-Pagination-item--firstPage ais-Pagination-item--disabled"
    >
      <span class="ais-Pagination-link" aria-label="First">‹‹</span>
    </li>
    <li
      class="ais-Pagination-item ais-Pagination-item--previousPage ais-Pagination-item--disabled"
    >
      <span class="ais-Pagination-link" aria-label="Previous">‹</span>
    </li>
    <li class="ais-Pagination-item ais-Pagination-item--selected">
      <a class="ais-Pagination-link" href="#">1</a>
    </li>
    <li class="ais-Pagination-item ais-Pagination-item--page">
      <a class="ais-Pagination-link" href="#">2</a>
    </li>
    <li class="ais-Pagination-item ais-Pagination-item--page">
      <a class="ais-Pagination-link" href="#">3</a>
    </li>
    <li class="ais-Pagination-item">
      <a class="ais-Pagination-link" href="#">4</a>
    </li>
    <li class="ais-Pagination-item ais-Pagination-item--nextPage">
      <a class="ais-Pagination-link" aria-label="Next" href="#">›</a>
    </li>
    <li class="ais-Pagination-item ais-Pagination-item--lastPage">
      <a class="ais-Pagination-link" aria-label="Last" href="#">››</a>
    </li>
  </ul>
</div>
```

## Customize the UI with `connectPagination`

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

To use `connectPagination`, you can import it with the declaration relevant to how you installed InstantSearch.js.

<CodeGroup>
  ```js Package manager theme={"system"}
  import { connectPagination } from 'instantsearch.js/es/connectors';
  ```

  ```js CDN theme={"system"}
  const { connectPagination } = instantsearch.connectors;
  // or directly use instantsearch.connectors.connectPagination()
  ```
</CodeGroup>

Then it's a 3-step process:

```js JavaScript icon=code theme={"system"}
// 1. Create a render function
const renderPagination = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customPagination = connectPagination(renderPagination);

// 3. Instantiate
search.addWidgets([
  customPagination({
    // 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).

```js JavaScript icon=code theme={"system"}
const renderPagination = (renderOptions, isFirstRender) => {
  const {
    pages,
    currentRefinement,
    nbHits,
    nbPages,
    isFirstPage,
    isLastPage,
    canRefine,
    refine,
    createURL,
    widgetParams,
  } = renderOptions;

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

  // Render the widget
};
```

<Note>
  If SEO is important for your search page, ensure that your custom HTML is optimized for search engines:

  * Use `<a>` tags with `href` attributes to allow search engine bots to follow links.
  * Use semantic HTML and include [structured data](https://developers.google.com/search/docs/appearance/structured-data) when relevant.

  For more guidance, see the [SEO checklist](/doc/guides/building-search-ui/resources/seo/js).
</Note>

#### Rendering options

<ParamField body="pages" type="number[]">
  The pages relevant to the current situation and padding.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { pages } = renderOptions;

    document.querySelector('#pagination').innerHTML = `
      <ul>
        ${pages
          .map(
            page => `
              <li>
                <a href="#">${page + 1}</a>
              </li>
            `
          )
          .join('')}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="currentRefinement" type="number">
  The number of the page currently displayed.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { pages, currentRefinement } = renderOptions;

    document.querySelector("#pagination").innerHTML = `
      <ul>
        ${pages
          .map(
            (page) => `
              <li>
                <a
                  href="#"
                  style="font-weight: ${currentRefinement === page ? "bold" : ""}"
                >
                  ${page + 1}
                </a>
              </li>
            `,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="nbHits" type="number">
  The number of hits computed for the last query (can be approximate).

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { currentRefinement, nbPages, nbHits } = renderOptions;

    document.querySelector("#pagination").innerHTML = `    <span>
        ${currentRefinement + 1} of ${nbPages} page(s) for ${nbHits} hit(s)
      </span>
   `;
  };
  ```
</ParamField>

<ParamField body="nbPages" type="number">
  The number of pages for the result set.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { currentRefinement, nbPages, nbHits } = renderOptions;

    document.querySelector("#pagination").innerHTML = `
      <span>
        ${currentRefinement + 1} of ${nbPages} page(s) for ${nbHits} hit(s)
      </span>
    `;
  };
  ```
</ParamField>

<ParamField body="isFirstPage" type="boolean">
  Whether the current page is the first page.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { pages, isFirstPage, isLastPage } = renderOptions;

    document.querySelector("#pagination").innerHTML = `
      <ul>
        ${
          !isFirstPage
            ? `
              <li>
                <a href="#">Previous</a>
              </li>
              `
            : ""
        }
        ${pages
          .map(
            (page) => `
              <li>
                <a href="#">
                  ${page + 1}
                </a>
              </li>
            `,
          )
          .join("")}
        ${
          !isLastPage
            ? `
              <li>
                <a href="#">Next</a>
              </li>
              `
            : ""
        }
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="isLastPage" type="boolean">
  Whether the current page is the last page.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { pages, isFirstPage, isLastPage } = renderOptions;

    document.querySelector("#pagination").innerHTML = `
      <ul>
        ${
          !isFirstPage
            ? `
              <li>
                <a href="#">Previous</a>
              </li>
              `
            : ""
        }
        ${pages
          .map(
            (page) => `
              <li>
                <a href="#">
                  ${page + 1}
                </a>
              </li>
            `,
          )
          .join("")}
        ${
          !isLastPage
            ? `
              <li>
                <a href="#">Next</a>
              </li>
              `
            : ""
        }
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="canRefine" type="boolean" required>
  Indicates if search state can be refined.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { canRefine } = renderOptions;

    if (!canRefine) {
      document.querySelector("#pagination").innerHTML = "";
      return;
    }
  };
  ```
</ParamField>

<ParamField body="refine" type="function">
  Sets the current page and triggers a search.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { pages, currentRefinement, refine } = renderOptions;

    const container = document.querySelector("#pagination");

    container.innerHTML = `
      <ul>
        ${pages
          .map(
            (page) => `
              <li>
                <a
                  href="#"
                  data-value="${page}"
                  style="font-weight: ${currentRefinement === page ? "bold" : ""}"
                >
                  ${page + 1}
                </a>
              </li>
            `,
          )
          .join("")}
      </ul>
    `;

    [...container.querySelectorAll("a")].forEach((element) => {
      element.addEventListener("click", (event) => {
        event.preventDefault();
        refine(event.currentTarget.dataset.value);
      });
    });
  };
  ```
</ParamField>

<ParamField body="createURL" type="function">
  Generates a URL for the next state.
  The number is the page to generate the URL for.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { pages, createURL } = renderOptions;

    document.querySelector("#pagination").innerHTML = `
      <ul>
        ${pages
          .map(
            (page) => `
              <li>
                <a href="${createURL(page)}">
                  ${page + 1}
                </a>
              </li>
            `,
          )
          .join("")}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="widgetParams" type="function">
  All original widget options forwarded to the render function.

  ```js JavaScript icon=code theme={"system"}
  const renderPagination = (renderOptions, isFirstRender) => {
    const { widgetParams } = renderOptions;

    widgetParams.container.innerHTML = "...";
  };

  // ...

  search.addWidgets([
    customPagination({
      container: document.querySelector("#pagination"),
    }),
  ]);
  ```
</ParamField>

### Create and instantiate the custom widget

First, create your custom widgets using a rendering function.
Then, instantiate them with parameters.

There are two kinds of parameters you can pass:

* **Instance parameters**. Predefined options that configure Algolia's behavior.
* **Custom parameters**. Parameters you define to make the widget reusable and adaptable.

Inside the `renderFunction`, both instance and custom parameters are accessible through `connector.widgetParams`.

```js JavaScript icon=code theme={"system"}
const customPagination = connectPagination(renderPagination);

search.addWidgets([customPagination({ totalPages: number, padding: number })]);
```

#### Instance options

<ParamField body="totalPages" type="number">
  The total number of pages to browse.

  ```js JavaScript icon=code theme={"system"}
  customPagination({
    totalPages: 4,
  });
  ```
</ParamField>

<ParamField body="padding" type="number" default={3}>
  The padding of pages to show around the current page

  ```js JavaScript icon=code theme={"system"}
  customPagination({
    padding: 2,
  });
  ```
</ParamField>

### Full example

<CodeGroup>
  ```html HTML theme={"system"}
  <div id="pagination"></div>
  ```

  ```js JavaScript theme={"system"}
  // Create the render function
  const renderPagination = (renderOptions, isFirstRender) => {
    const {
      pages,
      currentRefinement,
      nbPages,
      isFirstPage,
      isLastPage,
      refine,
      createURL,
    } = renderOptions;

    const container = document.querySelector("#pagination");

    container.innerHTML = `
      <ul>
        ${
          !isFirstPage
            ? `
              <li>
                <a
                  href="${createURL(0)}"
                  data-value="${0}"
                >
                  First
                </a>
              </li>
              <li>
                <a
                  href="${createURL(currentRefinement - 1)}"
                  data-value="${currentRefinement - 1}"
                >
                  Previous
                </a>
              </li>
              `
            : ""
        }
        ${pages
          .map(
            (page) => `
              <li>
                <a
                  href="${createURL(page)}"
                  data-value="${page}"
                  style="font-weight: ${currentRefinement === page ? "bold" : ""}"
                >
                  ${page + 1}
                </a>
              </li>
            `,
          )
          .join("")}
          ${
            !isLastPage
              ? `
                <li>
                  <a
                    href="${createURL(currentRefinement + 1)}"
                    data-value="${currentRefinement + 1}"
                  >
                    Next
                  </a>
                </li>
                <li>
                  <a
                    href="${createURL(nbPages - 1)}"
                    data-value="${nbPages - 1}"
                  >
                    Last
                  </a>
                </li>
                `
              : ""
          }
      </ul>
    `;

    [...container.querySelectorAll("a")].forEach((element) => {
      element.addEventListener("click", (event) => {
        event.preventDefault();
        refine(event.currentTarget.dataset.value);
      });
    });
  };

  // Create the custom widget
  const customPagination = connectPagination(renderPagination);

  // Instantiate the custom widget
  search.addWidgets([
    customPagination({
      container: document.querySelector("#pagination"),
    }),
  ]);
  ```
</CodeGroup>
