Skip to content

Instantly share code, notes, and snippets.

@victorbruce
Last active January 3, 2022 03:22
Show Gist options
  • Save victorbruce/c9bb1076cbc25719eeacd7c43c91404d to your computer and use it in GitHub Desktop.
Save victorbruce/c9bb1076cbc25719eeacd7c43c91404d to your computer and use it in GitHub Desktop.
Paginating, Filtering, and Sorting in React

Pagination

To paginate a page, a general algorithm needs to be followed. Also, you should have the following variables in place:

  • Total items availabe or Items count (It can be a list of patients, books, etc coming from the database)
  • Number of items to display per page or Page size
  • Page count or number of pagination buttons to be rendered (**NB:**This needs to be calculated)

Calculation: Now once you know the total items available as well as the number of items to display per page or page size, we can go ahead to calculate the number of pages we can have(page1, page2, page3, etc).

So page count is calculated as :

  const pageCount = Math.ceil(itemsCount/pageSize);

Paginate the data

To paginate the data on the page, we need to have access to three things. The total items, pageNumber, pageSize. Using loadash,

  function paginate(items, pageNumber, pageSize) {
    // get the starting index
    const startIndex = (pageNumber - 1) * pageSize;
    // slice data from items based on the starting index
    _.(items).slice(items, startIndex).take(pageSize).value();
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment