DEV Community

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

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!