I am building pagination where I want to display '...' at certain points. The amount of pages is dictated by user selection; there are 650-ish posts, and users can choose to display 15, 25, 50, or 100 items at a time. Anyway, let's say that there are 45 pages. If I am on page one, I want it to look like this:
1 2 3 ... 45
if I am on page 3, I want it to look like this:
1 ... 2 3 4 ... 45
if I am on page 44 (or 45), I want it to look like this:
1... 43 44 45
I am doing this all with JS, I'm not using any extra pagination packages from React. Currently, I have some functionality but I am getting stumped on how to adjust my for loop.
So, right now, if I am on page 1, it looks like :
1 2 ... 43 44 45
If I'm on page 3 :
1 2 3 4 ... 43 44 45
If I am on page 4:
1... 3 4 5 ... 43 44 45
**If I am on page 45:
1 ... 44 45
I looked around for a long time, and finally found a stackoverflow thread that helped. I implemented the basic while loop provided by derpirscher.
let pagination = [], i = 1;
while (i <= totalPageCount) {
if (i <= 1 ||
i >= totalPageCount - 2||
i >= currentPage - 1 && i <= currentPage + 1) {
pagination.push(i);
i++;
} else {
pagination.push('...');
//jump to the next page to be linked in the navigation
i = i < currentPage ? currentPage - 1 : totalPageCount - 2;
}
}
In this example, totalPageCount is how many pages there are total, and currentPage is the page the user is currently on. I tried to incorporate some sibling logic where if, for example, the left sibling index was greater than two, I inserted dots. That just resulted in there being dots on the left side of just about every page number, and I definitely didn't want that.
If it is important, I map through pagination directly in my render function to generate the template.
{pagination.map((pageNumber) => {
return (
<li key={pageNumber}>
<button
onClick={() => onPageChange(pageNumber)}
>
{pageNumber}
</button>
</li>
)
})}
Any thoughts or useful resources on this would be appreciated. I know my JS could be better, which is partly why I am trying to practice doing it this way!