DEV Community

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

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

damilola jerugba on October 09, 2021

This guide is to help you understand the concept of pagination and how to implement it in react, the concepts in this tutorial can be applied to an...
Collapse
 
damiisdandy profile image
damilola jerugba • Edited

Hi Everyone, I've noticed most of you guys are requesting for features like the ability for the repo to handle more than 1000 pages, the usePagination() hook can handle ∞ number of pages. But you guys are should understand that this blog post is simply to show the usePagination() hook and has nothing to do with the pagination buttons or styling. Some of you are requesting that I should add the UI functionality of ... in the middle of the pagination buttons for pages that are as large as a 100 pages. This require for the usePagination() hook to also return a component that contains the pagination buttons.

If you'd like me to implement this, please get the github repo to 50 stars and i'll convert this into a full library that tackles these issues and more.

You are also free to collaborate on this repo so we can build it as a library together πŸ’™

Thank you πŸ’™πŸ’™πŸ’™πŸ’™

Collapse
 
mbrookes profile image
Matt

Here's a fully functional usePagination hook, with a demo of rendering buttons and an ellipsis: mui.com/components/pagination/#use...

Collapse
 
damiisdandy profile image
damilola jerugba

That’s great, but you’ll need install the β€˜@mui’ library to use it

Thread Thread
 
mbrookes profile image
Matt

Well, sure, but that's a single command (yarn add or npm install). And since all you import is the hook, that's all that will be included in your bundle.

Thread Thread
 
damiisdandy profile image
damilola jerugba

I'll try that, but I'll still challenge myself and create a npm package, it will be my first open source project

Thread Thread
 
mbrookes profile image
Matt

Of course! And perhaps you’ll find a more elegant implementation. It’s a tricky problem to solve! Good luck! πŸ‘

Collapse
 
jcubic profile image
Jakub T. Jankiewicz

Do you have a working demo? Does't it work with 1000 pages?

Collapse
 
damiisdandy profile image
damilola jerugba

The number of pages fully depend on the contentPerPage, the API route I used in the code only returns an array of 20 items so the maximum possible number of pages is either 1 or 20, with 3 contentPerPage it generated 7 pages

Here is a working demo => use-pagination.vercel.app/

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

So it's not fully functional pagination. Just a simple demo.
Here is example how pagination should work (the code is in PHP but it's algorithm that can be rewritten in any language).
gist.github.com/bramus/5d8f2e0269e...

Also note that prev should be disabled when on first page.

Thread Thread
 
damiisdandy profile image
damilola jerugba

It's functional, I was referring to Typescript you were talking about types. There are many ways to implement pagination, this is just my way, and this will work for any language

Thread Thread
 
jcubic profile image
Jakub T. Jankiewicz • Edited

It's functional, I was referring to Typescript you were talking about types.

I don't quite understand what you write this above comment. I just mean that this is not fully implemented pagination, because it's missing fundamental features. So it can't be used in any real projects. You need to implement the thing yourself if you want to have something that is a full pagination. Also this will not work with any language because it's like half of the implementation.

Thread Thread
 
damiisdandy profile image
damilola jerugba • Edited

Sorry I thought I replied to another comment, could you list out these features, so I improve this React hook

Thread Thread
 
damiisdandy profile image
damilola jerugba

You are also free to make contributions to the repo

Thread Thread
 
jcubic profile image
Jakub T. Jankiewicz

Added two issues. I may contribute if the issue is not fixed when I will need pagination since I will need something like this in the near future for my application.

Thread Thread
 
damiisdandy profile image
damilola jerugba

πŸ‘πŸ½

Collapse
 
roblevintennis profile image
Rob Levin

Thanks for this article @damiisdandy β€” the illustrations are very helpful and I appreciate the time you spent to share this with the community! Very happy you used buttons too :)

I coded this up for my AgnosticUI library and found my SRP cohesion was best when I made my usePagination.ts hook only concerned with generating the paging links. Then my Pagination.tsx provided the React view and the consumer could simply DI inject the generated pages into the component. The consumer actually keeps track of const [currentPage, setCurrentPage] = useState(1) and listens for a onPageChanged callback resulting in updating the current page. That in turn triggers the useEffect that just asks for the pages to be regenerated with the new current page. It all seems to work quite nicely!

Also, I looked at many many examples on the web and found one somewhere that utilizes currying and utilized that approach as it's extremely efficient and readable:

  const generatePagingPaddedByOne = (current: number, totalPageCount: number) => {
    const center = [current - 1, current, current + 1];
    const filteredCenter: PageArrayItem[] = center.filter((p) => p > 1 && p < totalPageCount);
    const includeLeftDots = current > 3;
    const includeRightDots = current < totalPageCount - 2;
    return getPaddedArray(filteredCenter, includeLeftDots, includeRightDots, totalPageCount);
  };
Enter fullscreen mode Exit fullscreen mode

My API allows you to use 1 or 2 for padding (I've also seen this called one of: "gap" or "offset" or "siblingCount"). Looking at Ant Design and Zen Garden, they both used padding of 1 on both sides but I think 2 is nice to have as an option. The curry approach above is so crystal clear it almost feels like cheating, but, it's also very efficient for large data sets. Thoughts?

I'm actually work-in-progress on this so I don't have a link with live example but I've completed (I think) my React implementation here: pagination component and pagination hook. It gives tabbing for free since it uses buttons (quite similar to how you've done I think; yay for using semantic elements!)

I wonder if this might be an interesting alternative approach for these folks asking about > 1k pages as the curry approach isn't affected by size nor does it require a massive loop. Wish I could take credit but I saw it in a gist "somewhere" and adapted it to my needs. What a challenging programming task to write a good pagination! I'd fail this in a timed interview for sure lol

Collapse
 
damiisdandy profile image
damilola jerugba

Thanks so much, and your idea is solid!

Collapse
 
praveen_g profile image
Prawin G

Hi @damiisdandy just a small doubt,
In changePage function how does state variable work ?
And what's the difference between props data type with and without it ?
say (x : number) || (x)

Btw great code

Collapse
 
damiisdandy profile image
damilola jerugba

the changePage function simply takes in a boolean of either true or false, if true the page state is incremented, and if false the page state is decremented.

there is no functional difference between adding a data type, this is just used so you can't predict the type of value used in the function later and to aid IntelliSense in your IDE. if a data type is not provided typescript will read it as a type of any which is okay.

Also with the useState() hook setPage() can either take in a number or a function that returns a number, which is what I used.

Collapse
 
harryheman profile image
Igor Agapov
setPage: (n: number) => void

const usePagination = ({
  contentPerPage,
  count
}: UsePaginationProps): UsePaginationReturn => { /* ... */ }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
damiisdandy profile image
damilola jerugba

usePaginationReturn is an interface for an object not a function.


type UsePagination = (UsePaginationProps) => (UsePaginationReturn);
const usePagination: UsePagination = ({ contentPerPage, count }) => {  /*...*/ }

Enter fullscreen mode Exit fullscreen mode

The above type is the correct implementation.

Collapse
 
harryheman profile image
Igor Agapov

usePaginationReturn is an interface for an object, returning from a function, so this

type UsePagination = (UsePaginationProps) => (UsePaginationReturn);
const usePagination: UsePagination = ({ contentPerPage, count }) => {  /*...*/ }
Enter fullscreen mode Exit fullscreen mode

is equivalent to this

const usePagination = ({ contentPerPage, count }: UsePaginationProps): UsePaginationReturn => { /* ... */ }
Enter fullscreen mode Exit fullscreen mode

Just -1 type

Collapse
 
theharshrastogi profile image
Harsh Rastogi

Nice

Collapse
 
damiisdandy profile image
damilola jerugba

Thanks, glad you liked it

Collapse
 
rag_marcus_321 profile image
Raghav Gupta

Awesome

Collapse
 
damiisdandy profile image
damilola jerugba

Thanks πŸ‘πŸ½

Collapse
 
shaalanmarwan profile image
Shaalan Marwan

Very clear , thanks

Collapse
 
damiisdandy profile image
damilola jerugba

You are welcome ❀️

Collapse
 
damiisdandy profile image
damilola jerugba

Thank you ⚑

Collapse
 
tzii profile image
Vu

it doesn't work when you have many pages like more than 100

Collapse
 
damiisdandy profile image
damilola jerugba

Can you share a piece of the code you wrote, 100 pages depends on the content per page. It should work for any number.

Collapse
 
damiisdandy profile image
damilola jerugba

Follow me on github and twitter