usePagination

A React Hook that manage pagination state.

Demo

Source
Total count:
100
Page size:
Current page:
1
Page count:
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Target Page:

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const [pagination, pagiActions] = usePagination(options)

Options

export type UsePaginationOptions = {
  /**
   * Total number of items.
   *
   * @defaultValue Number.POSITIVE_INFINITY
   */
  total?: number
  /**
   * The number of items to display per page.
   *
   * @defaultValue 10
   */
  pageSize?: number
  /**
   * The current page number.
   *
   * @defaultValue 1
   */
  page?: number
  /**
   * Callback when the `page` change.
   */
  onPageChange?: (pagination: UsePaginationReturnsState) => void
  /**
   * Callback when the `pageSize` change.
   */
  onPageSizeChange?: (pagination: UsePaginationReturnsState) => void
  /**
   * Callback when the `pageCount` change.
   */
  onPageCountChange?: (pagination: UsePaginationReturnsState) => void
}

Returns

export interface UsePaginationReturnsState<T = any> {
  /**
   * Total number of items.
   */
  total: number
  /**
   * The current page number.
   *
   * @deprecated Use `page` instead.
   */
  currentPage: number
  /**
   * The number of items to display per page.
   *
   * @deprecated Use `pageSize` instead.
   */
  currentPageSize: number
  /**
   * The current page number.
   */
  page: number
  /**
   * The number of items to display per page.
   */
  pageSize: number
  /**
   * The total number of pages.
   */
  pageCount: number
  /**
   * The start index of the displayed list (helpful to slice the list).
   */
  indexStart: number
  /**
   * The end index of the displayed list (helpful to slice the list).
   */
  indexEnd: number
  /**
   * The start count of the displayed list.
   */
  countStart: number
  /**
   * The end count of the displayed list.
   */
  countEnd: number
  /**
   * Whether the current page is the first page.
   */
  isFirstPage: boolean
  /**
   * Whether the current page is the last page.
   */
  isLastPage: boolean
  /**
   * The sliced list to display.
   */
  list: T[]
}

export interface UsePaginationReturnsActions {
  /**
   * Go to the previous page.
   *
   * @returns {void} `void`
   */
  prev(): void
  /**
   * Go to the next page.
   *
   * @returns {void} `void`
   */
  next(): void
  /**
   * Go to the specified page.
   *
   * @param {number} page - `number`, the page number
   * @returns {void} `void`
   */
  go: (page: number) => void
  /**
   * Set the number of items to display per page.
   *
   * @param {number} size - `number`, the number of items to display per page
   * @returns {void} `void`
   */
  setPageSize: (size: number) => void
}

export type UsePaginationReturns = readonly [UsePaginationReturnsState, UsePaginationReturnsActions]