Generate a sequence of numbers for use in a pagination system, the clever way.

Last update: Jun 5, 2022

JavaScript Pagination Sequence Generator

JavaScript Pagination Sequence Generator

Generate a sequence of numbers for use in a Pagination Component, the clever way.

Installation

npm i @bramus/pagination-sequence

Usage / Example

This library comes as an ES Module and exposes a function/algorithm to generate an array of pagination entries.

import { generate } from '@bramus/pagination-sequence';

const sequence = generate(67, 74);
// ~> [1, 2, '…', 65, 66, 67, 68, 69, '…', 73, 74]

Note that this is a Framework Agnostic library: the generated array is not rendered in any way but, instead, must be fed into your own Pagination Component for rendering.

💡 Looking for some Pagination Component inspiration? See Integration Examples below to see how to use this with the JavaScript Framework Du Jour™.

API

The exposed function has the following API:

generate(curPage, numPages, numberOfPagesAtEdges = 2, numberOfPagesAroundCurrent = 2, glue = '…');

Parameters:

  • curPage: The current active page
  • numPages: The total number of pages
  • numberOfPagesAtEdges (default: 2): Number of pages to show on the outer edges.
  • numberOfPagesAroundCurrent (default: 2): Number of pages to show around the active page.
  • glue (default: '…'): The string to show when there's a gap

Principles

The algorithm is opinionated and follows these principles:

  • Stable Output

    When generating a sequence, it will always generate the same amount of entries, for any curPage value. When viewing a page at the edge of a series, this can result in numberOfPagesAtEdges being ignored.

    For example: Instead of having generate(2, 12, 1, 1) return 01-[02]-03-..-12 (5 entries), it will return 01-[02]-03-04-05-..-12 (7 entries). This is a deliberate choice because generate(7, 12, 1, 1) will also return 7 entries: 01-..-06-[07]-08-..-12.

    With a stable amount of entries being generated, the output will also be visually stable when rendered on screen.

  • Always include links to the edges

    The algorithm will always include links to the first and last page.

    For Example: when looking at page 25 of 50, the algorithm will include a link to page 1 and page 50.

  • No unnecessary gaps

    When the algorithm detects a gap that's only “1 item wide”, it will replace that gap with the actual number.

    For Example: A foolish take on generate(4, 9, 1, 1), would generate 01-..-03-[04]-05-..-09. The algorithm corrects the first gap to 02 and will return 01-02-03-[04]-05-..-09 instead.

Integration Examples

React

🔗 Try it online: https://codepen.io/bramus/pen/NWaxNKQ

import React from "react";
import ReactDOM from "react-dom";
import { generate } from "@bramus/pagination-sequence";

const BASE_URL = '#';

const PaginationEntry = ({ value, onEntryClick = null, label = null, title = null, isCurrent = false, isDisabled = false, ...props }) => {
    label ??= value;
    title ??= `Go to page ${value}`;

    const onClick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        
        e.target.blur();
        
        if (onEntryClick) {
            onEntryClick(value);
        }
    }
        
    if (value == '…') {
        return (
            <li data-pagination-ellipsis {...props}><span>{label}</span></li>
        );
    }

    if (isDisabled) {
        return (
            <li data-pagination-disabled {...props}><span>{label}</span></li>
        );
    }

    if (isCurrent) {
        props['data-pagination-current'] = true;
    }

    return (
        <li {...props}>
            <a href={`${BASE_URL}/page/${value}`} title={title} onClick={onClick}>{label}</a>
        </li>
    );
}

const Pagination = ({ curPage, numPages, numPagesAtEdges = 2, numPagesAroundCurrent = 2, onEntryClick = null }) => {
    const sequence = generate(curPage, numPages, numPagesAtEdges, numPagesAroundCurrent);
    // console.log(sequence);

    return (
        <ul className="pagination">
            <PaginationEntry data-pagination-first onEntryClick={onEntryClick} value={1} title="Go to First Page" label="&laquo;" isDisabled={curPage === 1} />
            <PaginationEntry data-pagination-prev onEntryClick={onEntryClick} value={curPage-1} title="Go to Previous Page" label="&lsaquo;" isDisabled={curPage === 1} />
            {sequence.map((val, idx) => 
                <PaginationEntry key={`page-${(val == '…') ? `…-${idx}` : val}`} onEntryClick={onEntryClick} value={val} isCurrent={val == curPage} />
            )}
            <PaginationEntry data-pagination-next onEntryClick={onEntryClick} value={curPage+1} title="Go to Next Page" label="&rsaquo;" isDisabled={curPage === numPages} />
            <PaginationEntry data-pagination-next onEntryClick={onEntryClick} value={numPages} title="Go to Last Page" label="&raquo;" isDisabled={curPage === numPages} />
        </ul>
    );
}

ReactDOM.render(
    <Pagination curPage={25} numPages={50} onEntryClick={(val) => { console.log(val)}} />,
    document.getElementById('root')
);

License

@bramus/pagination-sequence is released under the MIT public license. See the enclosed LICENSE for details.

Other Language Implementations

Looking for an implementation in another programming language?

GitHub

https://github.com/bramus/js-pagination-sequence
You might also like...

A ReactJS dumb component to render a pagination

A ReactJS dumb component to render a pagination

react-js-pagination A ReactJS dumb component to render a pagination. The component comes with no built-in styles. HTML layout compatible with Bootstra

Apr 22, 2022

React - Pagination Example with logic like Google

react-pagination-example React - Pagination Example with Logic like Google To see a demo and further details go to http://jasonwatmore.com/post/2017/0

Jun 7, 2022

Simple, lightweight, flexible pagination ReactJS component ⏮⏪1️⃣2️⃣3️⃣⏩⏭

Simple, lightweight, flexible pagination ReactJS component ⏮⏪1️⃣2️⃣3️⃣⏩⏭

React Paginating Motivation During development, we were facing problems supporting server-rendering of our web app & SEO (require pagination links). T

Jun 14, 2022

simple library for pagination in react

IMPORTANT NOTE This repository is DEPRECATED. Please use react-pagination-js instead which has more added feature and is tested well. React-pagination

Jan 24, 2020

React Pagination Component.

React Pagination Component.

Jun 18, 2022

React Pagination using Hooks example

React Pagination using Hooks example Set port .env PORT=8081 Project setup In the project directory, you can run: npm install # or yarn install or C

Apr 20, 2022

React Pagination Bar

React Pagination Bar

React Pagination Bar Lightweight component for pagination of application pages on react Features Customizing class names without using style overrides

Jan 26, 2022

Get-random-numbers-lotery - App to create randomic numbers for lotery bet (six numbers sequences)

Get-random-numbers-lotery - App to create randomic numbers for lotery bet (six numbers sequences)

Get-random-numbers-lotery - App to create randomic numbers for lotery bet (six numbers sequences)

Jan 22, 2022

Personal blog and portfolio with a basic comment system created with react, php and mysql, hosted on github pages and backend hosted on heroku and clever cloud for free!

Personal blog and portfolio with a basic comment system created with react, php and mysql, hosted on github pages and backend hosted on heroku and clever cloud for free!

Personal blog and portfolio with a basic comment system created with react, php and mysql, hosted on github pages and backend hosted on heroku and clever cloud for free!

Mar 16, 2022

A converter from binary numbers to decimal numbers.

A converter from binary numbers to decimal numbers.

Um conversor de números binários para números decimais

Oct 21, 2021

⚡️The Fullstack React Framework — built on Next.js

⚡️The Fullstack React Framework — built on Next.js

⚡️The Fullstack React Framework — built on Next.js

Jun 16, 2022

⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

Oct 12, 2021

Use-step-animation - Custom hook used to make sequence of animations using positions more easily

use-step-animation Custom hook used to make sequence of animations using positio

Jan 8, 2022

React.js pagination component based on ultimate-pagination

React.js pagination component based on ultimate-pagination

react-ultimate-pagination React.js pagination component based on ultimate-pagination. It's implemented as a higher-order component that allows easy in

Jun 4, 2022

Sweet Pagination - A ReactJS component to render a pagination

Sweet Pagination - A ReactJS component to render a pagination

Sweet Pagination - A ReactJS component to render a pagination

Jun 10, 2022

🔢 Generate react-native pickers with range numbers.

🔢 Generate react-native pickers with range numbers.

React Native Number Please 🙏🏽 Generate react-native pickers with range numbers. Example Installing Add the package to your project yarn add react-na

Jun 6, 2022

DashGo - A React application for dashboard's in general with pages and pagination, login and user inclusion system

DashGo - A React application for dashboard's in general with pages and pagination, login and user inclusion system

Ignite - Trilha ReactJS Sobre o projeto O projeto foi baseado no 4º módulo da tr

May 31, 2022

🐄 Easy way to generate open-graph images dynamically using Next.js API Routes. Suitable for serverless environment.

Next.js API OG Image · Simple library with purpose of providing easy way to dynamically generate open-graph images using Next.js API routes. If you're

Jun 16, 2022

react pagination component, simple use

react pagination component, simple use

React-pagination Preview: https://killsanghyuck.github.io/react-pagination/ Install npm install react-pagination-component Configuration totalPage :

Mar 18, 2022
Comments
  • 1. Object parameter for options

    Thanks for publishing this! 😄 Hoping to give it a try soon in 11ty; my current pagination is linear.

    I noticed that the current API makes it a little difficult to read examples like this since all of the arguments share the same type:

    generate(4, 9, 1, 1)
    

    There may also be situations where a user wants to customize just one option but not touch any of the others. e.g., if I want to specify a custom string for glue, I'll need to pass along all of the intermediate arguments as well.

    What are your thoughts on changing the API to accept an object instead? Maybe something like this:

    const generate = (options) => {
      const {
        curPage, 
        numPages, 
        numPagesAtEdges= 2,
        numPagesAroundCurrent = 2,
        glue = '…'
      } = options;
    }
    

    (This also proposes standardizing number => num, or vice versa, since the arguments would be named.)

    Reviewed by AleksandrHovhannisyan at 2021-12-06 14:10
  • 2. Getting ERR_MODULE_NOT_FOUND when trying to use readme code sample

    I'm unable to use the module; this may be user error, but I also tried writing tests for the package and ran into a similar error where both ava and jest were unable to find @bramus/range unless I changed the import to @bramus/range/dist/index.js.

    I think it may have something to do with the fact that the packages don't have a root index.js and instead export a dist folder.

    Steps to repro

    1. Create a blank package: npm init or yarn init.
    2. Step type: "module" in package.json.
    3. Install the package per the README: yarn add @bramus/pagination-sequence.
    4. Create an index.js with the following contents:
    import { generate } from '@bramus/pagination-sequence';
    
    const sequence = generate(67, 74);
    

    Run node index.js. Observe the following error:

    Error [ERR_MODULE_NOT_FOUND]: Cannot find package '/sandbox/node_modules/@bramus/pagination-sequence/' imported from /sandbox/index.js
    

    Changing the import statement to @bramus/pagination-sequence/dist/index.js works.

    Environment

    Node version: 16.13.0

    Reviewed by AleksandrHovhannisyan at 2021-12-11 19:06
  • 3. Check gap generation with adjusted numberOfPagesAtEdges value

    generate(34, 50, 3) generates:

    [1,2,3,'31',32,33,34,35,36,'…',48,49,50]
    

    Note that '31' is a string, right where the first '…' should be. All other curValue values work fine.

    Same with generate(14, 50, 1). Only that curValue fails:

    [1, '11', 12, 13, 14, 15, 16, '…', 50]
    

    💡 By no coincidence, it's '31' with a param of 3, and it's '11' when the param is 1. Seeing a pattern here …

    Reviewed by bramus at 2021-12-06 08:50
  • 4. Add a little bit more explanation

    • Explain reasoning (no unnecessary gaps, always show first/last, …)
    • Explain the parameters a bit more
    • Refer to initial version of https://gist.github.com/bramus/5d8f2e0269e57dff5136
    Reviewed by bramus at 2021-12-06 00:00
Sweet Pagination - A ReactJS component to render a pagination
Sweet Pagination - A ReactJS component to render a pagination

Sweet Pagination - A ReactJS component to render a pagination

Jun 10, 2022
react pagination component, simple use
react pagination component, simple use

React-pagination Preview: https://killsanghyuck.github.io/react-pagination/ Install npm install react-pagination-component Configuration totalPage :

Mar 18, 2022
A ReactJS component that creates a pagination
A ReactJS component that creates a pagination

react-paginate A ReactJS component to render a pagination. By installing this component and writing only a little bit of CSS you can obtain this: or I

Jun 25, 2022
Laravel Pagination with ReactJS (customizable)

Laravel Pagination with ReactJS (customizable) react-laravel-paginex will provide you ability to easily create pagination from Laravel Pagination obje

Jun 16, 2022
⚛️ React render props component & custom hook for pagination.

Paginated React render props & custom hook for pagination. Features Headless component - There are no restrictions on the ui expression. Style free -

May 22, 2022
A React component to render your pagination navigation

A React component to render your pagination navigation

Dec 12, 2021
React Pagination Utils

React Pagination Utils

May 26, 2022
HTML CSS & React - Pagination component
HTML CSS & React - Pagination component

React component to fetch GitHub followers and showcase certain amount at each page with pagination

May 8, 2022
React components for sorting, filtering and pagination of data.

react-data-components DataTable: Live demo and source SelectableTable: Live demo and source Getting started npm install react-data-components --save T

Apr 8, 2022
Simple pagination for React (MIT)

react-pagify - Simple pagination for React react-pagify provides a simple API for building your own custom paginator. If you want to learn more about

Jun 5, 2022