How to Build a Custom Pagination Component in React

Shubham Khatri
JavaScript in Plain English
7 min readAug 27, 2021

--

We often work with web applications that need to fetch large amounts of data from a server through APIs and render it on the screen.

For example, in a Social media application, we fetch and render users’ posts and comments. In an HR dashboard, we display information about candidates who applied for a job. And in an Email Client, we show the user’s emails.

Rendering all the data at once on the screen can cause your webpage to slow down considerably because of the large number of DOM elements present in the webpage.

If we want to optimize performance, we can adopt various techniques to render data more efficient. Some of these methods include infinite scroll with virtualization and pagination.

Pagination works well when you know the size of the data in advance, and you don’t make frequent additions or deletions to the data-set.

For instance, in a social media website where new posts are published every few milliseconds, pagination wouldn’t be an ideal solution. But it would work well for an HR dashboard where candidate applications are displayed and need to be filtered or sorted as well.

In this post, we will focus on pagination and we’ll build a custom-controlled component that handles page buttons based on the current page and total data count.

We will also write a custom React hook that gives us a range of numbers to be rendered by the pagination component. We can use this hook independently as well when we want to render a pagination component with different styles or in a different design.

Below is a demo of what we will be building in this tutorial:

Demo interaction of the final application

How to Set Up the Project

If you are familiar with setting up a React project, you can skip this section.

In order to set up our React Project, we will use the create-react-app command line package. You can install the package globally using npm install -g create-react-app or yarn add global create-react-app.

Run create-react-app from the command line to create a new project like this:

npx create-react-app react-pagination

Next, we need to install our dependencies. We will just be using a simple additional dependency called classnames which provides flexibility when handling multiple classNames conditionally.

To install it run npm install classnames or yarn add classnames .

Now, we can run our project using the below command:

yarn start

How to Define the Interface

Now that we have our project running, we’ll dive straight into our Pagination component.

Let’s first look at what values we need as props to our Pagination component:

  • totalCount: represents the total count of data available from the source.
  • currentPage:represents the current active page. We’ll use a 1-based index instead of a traditional 0-based index for our currentPage value.
  • pageSize: represents the maximum data that is visible on a single page.
  • onPageChange: callback function invoked with the updated page value when the page is changed.
  • siblingCount (optional): represents the min number of page buttons to be shown on each side of the current page button. Defaults to 1.
Illustration of different values siblingCount

From the pagination component, we’ll invoke the usePagination hook which will take in the following parameters to compute the page ranges: totalCount , currentPage , pageSize , siblingCount .

How to Implement the usePagination Hook

Below are the few things we need to keep in mind while implementing the usePagination hook:

  • Our pagination hook must return the range of numbers to be displayed in our pagination component as an array.
  • The computation logic needs to re-run when either currentPage, pageSize, siblingCount, or totalCount changes.
  • The total number of items returned by the hook should remain constant. This will avoid resizing our pagination component if the length of the range array changes while the user is interacting with the component.

Keeping the above things in mind let’s create a file called usePagination.js in our project src folder and start with the implementation.

Our code skeleton will be as follows:

If we look at the above code, we are using the useMemo hook to compute our core logic. The useMemo callback will run when any value in its dependency array changes.

Also, we are setting the defaultValue of our siblingCount prop to be 1 as it is an optional prop.

Before we go ahead and implement the code logic, let’s understand the different behaviors of the Pagination component. The below image contains the possible states of a pagination component:

Possible states of Pagination component

Note that there are four possible states for a pagination component. We’ll go over them one by one.

  • Total page count is less than the page pills we want to show. In such a case we just return the range from 1 to totalPageCount.
  • Total page count is greater than the page pills but only the right DOTS are visible.
  • Total page count is greater than the page pills but only the left DOTS are visible.
  • Total page count is greater than the page pills and both the left and the right DOTS are visible.

As a first step, we shall go about calculating the total pages from totalCount and pageSize as follows:

const totalPageCount = Math.ceil(totalCount / pageSize);

Notice that we are using Math.ceil to round of the number to the next higher integer value. This ensures that we are reserving an extra page for the remaining data.

Next, we’ll go ahead and implement a custom range function which takes in a start and end value and returns an array with elements from start to end:

Range method implementation

Finally, we’ll implement the core logic by keeping the above cases in mind.

usePagination Custom hook implementation

The idea of the implementation is that we identify the range of numbers we want to show in our pagination component and then join them together with the separators or DOTS when we return the final range.

For the first scenario where our totalPageCount is less than the total number of pills we calculated based on the other params, we just return a range of numbers 1..totalPageCount .

For the other scenarios, we go about identifying whether we need DOTS on the left or right side of the currentPage by calculating the left and right indices after including the sibling pills to the currentPage and then make our decisions.

Once we know where we want to show the DOTS, the rest of the calculations are quite straightforward.

How to Implement the Pagination Component

As I mentioned earlier, we’ll be using the usePagination hook in our pagination component and we'll map over the returned range to render them.

We create a Pagination.js file in our src folder and implement the code logic as follows:

Pagination Implementation

We do not render a Pagination component if there are fewer than two pages (and then we return null).

We render the Pagination component as a list with left and right arrows that handle the previous and next actions of the user. In between the arrows, we map over paginationRange and render the page numbers as pagination-items. If the page item is a DOT we render a Unicode character for it.

As special handling, we add a disabled class to the left/right arrow if the currentPage is the first or the last page, respectively. We disable pointer-events and update the styles of the arrow icons through CSS if the icon needs to be disabled.

We also add click event handlers to the page pills which will invoke the onPageChanged callback function with the updated value of currentPage.

Our CSS file will contain the following styles:

Pagination component styles

And that’s it!

Our generic pagination implementation is ready and we can use it anywhere in our codebase.

How to Use the Custom Pagination Component

As the last step, let’s incorporate this component in a small example.

For the scope of this article, we shall render static data in the form of a table. So let’s go ahead and do that first:

At this point our UI looks as follows:

Intermediate table component UI

Now to incorporate the Pagination component, we need two things.

  • First, we maintain a currentPage state.
  • Second, we calculate the data to be rendered for a given page and just map and render it.

For the purposes of this demo, we’ll keep the PageSize constant and set its value to 10 we can also provide a selector for the user to select the desired pageSize .

Once we have made changes, we can go ahead and render our Pagination component with the appropriate props.

With these changes in mind, our final code will be as follows:

Final Demo code

You can find the live demo for the implementation here:

Demo

Conclusion

In this article, we create a custom React hook usePagination and used it within our Pagination component. We also implemented a short demo that used this component.

Thank you for reading.

You can check out the full source code for this tutorial in this GitHub repository.

If you found this article helpful, do like and share this with your colleagues and friends. If you have any suggestions, please feel free to add them in the comments.

I also share tips and tricks related to web development with JavaScript and React on Twitter.

More content at plainenglish.io

--

--

Software Engineer at Meta | Passionate about Javascript, React and Web Development | Active Stackoverflow contributor