How to create pagination badges

  • 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.
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];
}

Example of usage in React

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Have you sent your entries yet?

Vodcast | Pink Cloud 9 Vodcast https://bit.ly/3ckNwjt

$inbank1.png

An Example Micro Front End With Kong

The Var, Let And Const Ways Of Creating Variables In JavaScript — What Makes One Different From…

Recover package.json with npm-collect

Why and How we setup Linting and formatting for your React(typescript) project at Fleetx.io

Learn Javascript for beginners — Blog

React Starter App

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aral Roca Gomez

Aral Roca Gomez

More from Medium

Angular Vs Vue: Which Framework to Choose in 2022?

HOW TO IMPLEMENT ANIMATE ON SCROLL IN ANGULAR WEB APPS — USING THE AOS LIBRARY

Why You Should Use VueJS

How to work with video overlay on the web 🎉