54
Create simple pagination UI [Part 1]
Pagination is a popular UI that appears in almost all web applications. We often use a pagination component from a library, but sometimes for some reason we need to create our pagination. In the article, I will show you a solution to create your own version of pagination.
Before we start, I will list some requirements for our pagination:
From the above requirement, we have a mockup for the pagination

In the mockup, we have:
In this part, we will focus on creating the pagination data. Firstly, I will create some basic functions
The function helps to create continuous page numbers of slide
const createContinuousNumbers = (start, end) => {
if (start === end) return [start]
return [start, ...createContinuousNumbers(start + 1, end)]
}
The functions to move slide to left and right
const moveSlideToRight = (slide, step = 1) => {
return slide.map(pageNumber => pageNumber + step)
}
const moveSlideToLeft = (slide, step = 1) => {
return slide.map(pageNumber => pageNumber - step)
}
The functions to get maximum and minimum number from slide
const getMaxPageNumberFromSlide = (slide) => Math.max(...slide)
const getMinPageNumberFromSlide = (slide) => Math.min(...slide)
The functions help to detect the position of a number with a number list. There are five areas where a page number can be in. We need 3 functions to detect the position of a number page. In the
out of range
area we can use one function to validate the page number. The over leftmost
and over rightmost
need to be handled by 2 functions to decide the slide should move right or left
const isOverLeftmostOfSlide = (pageNumber, slide) => {
return pageNumber < getMinPageNumberFromSlide(slide)
}
const isOverRightmostOfSlide = (pageNumber, slide) => {
return pageNumber > getMaxPageNumberFromSlide(slide)
}
const isOutOfRange = (min, max) => pageNumber => {
return pageNumber < min || pageNumber > max
}
Now we are ready to start writing the pagination logic. We will start with function
goTo
because the next
function equal goTo(currentPage + 1)
, prev
function equal goTo(currentPage - 1)
, last
function equal goTo(lastPage)
and first
function equal goTo(1)
There some results to show how this function work
const totalPage = 20
const slideWidth = 4
const currentPage = 1
const pagination = Pagination(currentPage, totalPage, slideWidth)
// { partition: [ [ 1, 2, 3, 4 ], [ 20 ] ], currentPage: 1 }
pagination.getState()
// { partition: [ [ 1, 2, 3, 4 ], [ 20 ] ], currentPage: 2 }
pagination
.next()
.getState()
//{ partition: [ [ 1, 2, 3, 4 ], [ 20 ] ], currentPage: 1 }
pagination
.next()
.prev()
.getState()
It depends on the requirements, you can modify the conditions to
goTo
function.This is my way to create pagination. I hope it makes sense to you. If you have another solution or feedback, please leave the comment
Thanks
54