React Pagination Utils

Last update: May 26, 2022

url-pagination

This project has 2 goals:

  • provide utilities to compute pagination params inside your React components
  • persist pagination params as a part of URL so a page can be reloaded and linked to (currently we support Next.js router).

See it in action

Live example: https://url-pagination.vercel.app

Code of the example: example/pages/index.tsx

Getting started

In your shell:

    yarn add next-url-pagination
    # or
    npm install next-url-pagination

In your component:

// ...
import { useUrlPagination } from 'url-pagination';

function MyComponent () {
  const pagination = useUrlPagination({ perPage: 6 });

  // use a data fetching library of your choice
  const { data, error } = useSWR<Response>(
    `/some-api/posts?offset=${pagination.offset}&limit=${pagination.perPage}`
  );
  
  return (
    <>
      <PostsList posts={data.posts}/>
      <MyPagination total={data.total} page={pagination.page} onChange={pagination.onChange}  />
    </>
  )
}

If you want to keep pagination in React state instead of URL, instead of useUrlPagination use usePagination.

useUrlPagination

useUrlPagination(args: UseUrlPaginationArgs): PageInfo has the following signature:

// pass to useUrlPagination
type UseUrlPaginationArgs = {
  perPage: number; // number of records per page
  page?: number = 0; // specify initial page or make the component controlled (if the value changes) 
  scrollToTop?: boolean = false; // scroll page to the top upon navigation
  hotkeys?: boolean = false; // use left/right arrows and page up/down to navigation through pagination
  total?: number; // specify total records, optional, but recommended, without it hotkey pagination won't know when the last page is reached
  pageKey?: string = 'page'; // under what key the current page is going to appear in URL
  perPageKey?: string 'size'; // under what key the page size is going to appear in URL
  shallowNavigation?: boolean = true; // if true performs shallow Next.js router navigation upon changes
  includeHref?: boolean = false; // this argument is passed through to returned results
}
// get as a result
type PageInfo = {
  perPage: number; // size of the page, how many records each page contains
  offset: number; // what's the offset from the start
  page: number; // current page, maybe seen as redundant because there's `offset`, but different APIs use different params, it's here for convenience
  onChange: (page: number) => void; // function to call when a page changes
  onPerPageChange: (perPage: number) => void;  // function to call when a page size changes
  pageKey: string; // see UseUrlPaginationArgs, passed through without changes
  hrefBuilder: (pageIndex: number) => string; // call this function to build a new URL path based on page number
  includeHref: boolean; // passed through from arguments
}

usePagination

usePagination(args: UsePaginationArgs): PageInfo has the following signature (PageInfo is the same as for UseUrlPaginationArgs):

// pass to usePagination
type UsePaginationArgs = {
  perPage: number; // number of records per page
  page?: number = 0; // specify initial page or make the component controlled (if the value changes) 
  scrollToTop?: boolean = false; // scroll page to the top upon navigation
  hotkeys?: boolean = false; // use left/right arrows and page up/down to navigation through pagination
  total?: number; // specify total records, optional, but recommended, without it hotkey pagination won't know when the last page is reached
}

calculatePage

Utility to return the current page index based on offset and page size

calculatePage = ({
  offset: number;
  perPage: number;
}): number

Pagination component

The "presentation" component is not included in this library, because it's likely going to look very different in each app, however, you can find an example implementation at example/components/Pagination/index.tsx

Tree shaking

To enable tree shaking and save some space you can import functions like so:

import useUrlPagination from 'url-pagination/useUrlPagination';
import usePagination from 'url-pagination/usePagination';
// ...

GitHub

https://github.com/TheRusskiy/url-pagination
You might also like...

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

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

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

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

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

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

JavaScript Pagination Sequence Generator Generate a sequence of numbers for use in a Pagination Component, the clever way. Installation npm i @bramus/

Jun 5, 2022

a react usePagination() hook

a react usePagination() hook

Pagination in Javascript and React, with a custom usePagination() hook

Jun 8, 2022

Declarative routing for React

Welcome to React Router · React Router is a lightweight, fully-featured routing library for the React JavaScript library. React Router runs everywhere

Jun 22, 2022
Comments
  • 1. Component logic duplication

    Indeed a good example of rendering same component with and without router. Exactly what I have been looking for But this example does not solve problem to one disadvantage I'm facing too: logic duplication

    Difference between PaginationWithUrl and PaginationWithState components in one single line (obviously)

    -const PaginationWithUrl = () => {
    +const PaginationWithState = () => {
    	const [total, setTotal] = useState<number | undefined>()
    -	const pagination = useUrlPagination({ perPage: 6, hotkeys: true, total });
    +	const pagination = usePagination({ perPage: 6, total });
    
    	const { data, error } = useSWR<Response>(
    		`/api/posts?offset=${pagination.offset}&limit=${pagination.perPage}`
    	);
    
    	useEffect(() => {
    		setTotal(data?.total)
    	}, [data?.total])
    
    	if (error) return <div>failed to load</div>;
    	if (!data) return <div>loading...</div>;
    
    	return (
    		<div>
    -			<h2 className="text-2xl mb-4">Pagination that uses URL:</h2>
    +			<h2 className="text-2xl mb-4">Pagination that uses state:</h2>
    			<ul className="mb-2">
    				{data.results.map((d, i) => (
    					<li key={i} className="p-1 list-disc">
    						{d}
    					</li>
    				))}
    			</ul>
    			<Pagination total={data.total} {...pagination} />
    		</div>
    	);
    };
    

    Yes, it's not critical and components are simple. But still - it is duplication.

    How this example can be improved to eliminate duplication, any idea?

    Reviewed by cpof-tea at 2022-04-14 16:32
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 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
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
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
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 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