Build Custom Pagination with React

Mohit Khandelwal
2 min readMay 24, 2021

We often get involved in building web applications where we need to fetch large sets of data records from a remote server, API, or a database. If you are building a payment system, for example, it could be fetching thousands of transactions. If it is a social media app, it could be fetching many user comments, profiles, or activities. Whatever the case may be, there are several solutions for presenting the data in a manner that does not overwhelm the end-user interacting with the app.

One method for handling large datasets is using Pagination. Pagination works effectively when you already know the size of the dataset (the total number of records in the dataset) upfront. Secondly, you only load the required chunk of data from the total dataset based on the end-users interaction with the pagination control. This is the technique used in displaying search results in Google Search.

In this blog, I will guide you to setup your code and build a custom Pagination component which can be used with any type of dataset and view.

Setting up the Project

Start a new React application using the create-react-app command. You can name the application whatever you’d like, for e.g. react-pagination

Next, you will install the dependencies needed for your application. First, use the terminal window to navigate to the project directory:

Run the following command to install the required dependencies, in this installing styled-components:

Creating the Pagination Component

In this step, you will create the Pagination component. The Pagination component renders the left, right arrow and all the page numbers.

First, let’s create a components directory in the src directory. Then, create a new Pagination.js file in the src/components director.

And add the following code snippet to it:

In above code, assuming max pages to show will be 20, more than 20 pages will show when user navigate to higher page.

Also renderPageNumber() function is taking care of all the logic required to generate page numbers on the basis of current page and total page.

Now, we can import and use this Pagination component across all types of data set, you just need to pass pagination object as a props.

--

--

Mohit Khandelwal

Experienced Software Engineer with skilled in React JS, JavaScript, HTML, CSS and Jest. Working as a Senior Technical Consultant at Xebia.