DEV Community

Cover image for Pagination in React.
Uddesh
Uddesh

Posted on

Pagination in React.

Pagination is a type of feature you can find everywhere Bloggin website or on any E-Commerce website are the most common examples.

A few days ago I was working on a project in which I need to implement a blogging feature. Especially a timeline page where all posts will be visible. Now users can't see all posts at a time so it's a good idea to paginate data.

Now, there are a whole lot of libraries that can provide the same functionality but I don't want to use them. I want to create my own implementation and I haven't done it before. So I started searching for implementation on google. After a few hours of searching, I got nothing.

I found a few solutions but they were way complicated to understand. So I came up with my own solution. This solution may not be perfect but it's working for me.

Ok, so here how started picturing it.

1) In most of the pagination components, there are 7-page switching buttons. If we have data of length more then 7 pages.

As shown I picture below.

Alt Text

2) We need an array of page numbers to iterate and create page switching buttons.

Here is the logic for returning an array to iterate over.

   if (total <= 7) {
      let arr = [];
      for (let i = 1; i <= total; i++) {
        arr.push(i);
      }
      setPages(arr);
      return;
    }
    if (active <= 4) {
      setPages([1, 2, 3, 4, 5, "...", total]);
    }
    if (active > 4 && active < total - 3) {
      setPages([1, "...", active - 1, active, active + 1, "...", total]);
    }
    if (active > total - 4) {
      setPages([1, "...", total - 4, total - 3, total - 2, total - 1, total]);
    }
Enter fullscreen mode Exit fullscreen mode

Here I have handled four cases.

  • If we have less content that will fit in less than 8 pages then we simply return an array with numbers from 1 - last page.

  • Now if we have content that will fit in more than 7 pages. We need 1 - 5 numbers and "..." and last page numbers like [1 2 3 4 5 ... 10] this. Also if the user clicks on page number 1 to 4. The array will be the same.

  • In the third case, we need pages like [1 ... 4 5 6 ... 10] this.

  • In fourth case pages will be [1 ... 6 7 8 9 10] this. (considering total pages are 10)

That's all. Take your time if you didn't get my point. Try to understand again. It's really simple.

This is a working example and code.

I hope it will help. See you soon.

Bye

Top comments (3)

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Never thought of this way, definitely gonna try itπŸ˜„πŸ˜„

Collapse
 
uddeshjain profile image
Uddesh

For sure.

Collapse
 
anshulnegitc profile image
Anshul Negi

Simple and precise.