DEV Community

Cover image for How to create pagination badges
Aral Roca
Aral Roca

Posted on • Originally published at aralroca.com

6

How to create pagination badges

Original article: https://aralroca.com/blog/pagination-badges

The purpose of this short article is to share a helper function to create typical paging badges. I have used this helper on several places and I think it can be useful for anyone who needs it.

Example of paging badges

The helper accepts a list of 3 options:

  • currentPage - The current page, which will determine how badges are displayed with separators.
  • pages - Total number of pages to display.
  • numBadges (optional). Number of badges to be generated, by default is 5.

It returns an array with the badges as number, filling null for the separators. This is implemented this way (in pure JavaScript instead of returning for example JSX) to reuse it everywhere: (P)React, Vue, Svelte, Angular... Even in Node or Deno.

export default function pagesBadges({ currentPage, pages, numBadges = 5 }) {
  const maxBadgesSide = numBadges - 2;

  // Without separators case
  // ex: [1, 2, 3, 4, 5]
  if (pages <= numBadges) {
    return Array.from({ length: pages }).map((v, i) => i + 1);
  }

  const sideBadges = Array.from({ length: numBadges - 1 });

  // With a separator at the end case
  // ex: [1, 2, 3, 4, null, 49]
  if (currentPage <= maxBadgesSide) {
    return [...sideBadges.map((v, i) => i + 1), null, pages];
  }

  // With a separator at the beginning case
  // ex: [1, null, 46, 47, 48, 49]
  if (currentPage > pages - maxBadgesSide) {
    return [1, null, ...sideBadges.map((v, i) => pages - i).reverse()];
  }

  // In the middle (separator left + right) case
  // ex: [1, null, 26, 27, 28, null, 49]
  sideBadges.pop();
  const curr = Math.floor(sideBadges.length / 2);
  const center = sideBadges.map((v, i) => currentPage - curr + i);

  return [1, null, ...center, null, pages];
}
Enter fullscreen mode Exit fullscreen mode

I've published the code in GitHub (~200 bytes) in case that you want to use it in your projects:

This code is not providing any UI component, but it gives you the logic. With it you'll be able to create your paging component with the library/framework you want, to your liking. This partly offers a lot of flexibility in terms of design.

Example of usage in React

Sandbox using the paging module in React:

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up