> ## 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.

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" 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>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="js"
    baseHref="/doc/api-reference/widgets/pagination"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
]}
  />
</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>
