DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  • Data Contracts as the "Circuit Breaker" for Model Reliability
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Trending

  • Alternative Structured Concurrency
  • Kafka and Spark Structured Streaming in Enterprise: The Patterns That Hold Up Under Pressure
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  1. DZone
  2. Data Engineering
  3. Data
  4. ReactJs Pagination: How Do You Page Your Data With React.js Pagination?

ReactJs Pagination: How Do You Page Your Data With React.js Pagination?

This tutorial explains how to page your data with ReactJs Pagination by providing codes and three case examples to assist you.

By 
sasi kiran user avatar
sasi kiran
·
Feb. 06, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
21.2K Views

Join the DZone community and get the full member experience.

Join For Free

What Is React.js Pagination?

Who doesn’t know what Pagination is? 

Imagine you are reading a book without any page numbers? It wouldn't be weird if there wasn't the concept of paging. So, if your friend asks you how many pages you finished, what will you answer? Or, let us take an even worse case; suppose somehow there is an incident that has happened, and you lost some pages from your book, and the book had really important information. Now, you have no idea which pages or which information you lost! That’s really scary, isn’t it? 

Going back through history, can you believe there used to be a time when books and documents used to be published without page numbers? Only after 1500 c, it became a common practice to publish books with page numbers. If only some genius would have figured out that before. 

Similarly, there is a concept of pagination in the digital world where we divide a document into discrete pages/electronic pages. These electronics pages are rendered on a web browser and are called web pages. Also, these pages and the content in these pages, which is supposed to be rendered are related to each other using React.js pagination.

Ways to Render Data

Progressive Loading

For the rendering of data, we also have an option of progressive loading instead of React.js pagination. A very successful example of progressive loading is the Facebook or Instagram newsfeed where we have an option of infinite scroll while the news feed keeps updating and renders. Or, a better way to say it is that it exposes as much information that they can deliver to an end-user.   

React.js Pagination

But, pagination has its own importance in terms of filtering and showing only relevant data. For example, the Google search engine. So, React.js pagination becomes crucial when a user is searching for particular information and not consuming any random information. There is an enormous number of inbuilt libraries that are available to handle pagination in web development, especially in the case of React. Also, there are a huge number of resources available which you can use directly to handle pagination for your application. 

Some of the NPM and other pagination libraries available are:

  • React-js-pagination
  • React-paginate
  • React-bootstrap/Pagination
It is also ideal to use these existing libraries instead of re-writing your own, the same as there is no need of reinventing the wheel. Instead, you can focus on other things. But, at the same time, it is also very important to know what is happening behind the scenes so that you can build and customize your application as needed without compromising any requirements. There is also a possibility of different logics being used for different reactjs pagination packages available. For the implementation of react-pagination into your application, read this great article. Here, I will be explaining about react-pagination with the help of the code below and some calculations. 
 
JavaScript
 




x
49


 
1
   getPager(totalItems, currentPage, pageSize) { 
2
// default to first page 
3
       currentPage = currentPage || 1; 
4

            
5
       // default page size is 10 
6
       pageSize = pageSize || 10; 
7

            
8
       // calculate total pages 
9
       var totalPages = Math.ceil(totalItems / pageSize); 
10

            
11
       var startPage, endPage; 
12
       if (totalPages <= 10) { 
13
           // less than 10 total pages so show all 
14
           startPage = 1; 
15
           endPage = totalPages; 
16
       } else { 
17
           // more than 10 total pages so calculate start and end pages 
18
           if (currentPage <= 6) { 
19
               startPage = 1; 
20
               endPage = 10; 
21
           } else if (currentPage + 4 >= totalPages) { 
22
               startPage = totalPages - 9; 
23
               endPage = totalPages; 
24
           } else { 
25
               startPage = currentPage - 5; 
26
               endPage = currentPage + 4; 
27
           } 
28
       } 
29

            
30
        // calculate start and end item indexes 
31
       var startIndex = (currentPage - 1) * pageSize; 
32
       var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1); 
33

            
34
        // create an array of pages to ng-repeat in the pager control 
35
       var pages = [...Array((endPage + 1) - startPage).keys()].map(i => startPage + i); 
36

            
37
       // return an object with all pager properties required by the view 
38
       return { 
39
           totalItems: totalItems, 
40
           currentPage: currentPage, 
41
           pageSize: pageSize, 
42
           totalPages: totalPages, 
43
           startPage: startPage, 
44
           endPage: endPage, 
45
           startIndex: startIndex, 
46
           endIndex: endIndex, 
47
           pages: pages 
48
       }; 
49
   }



Let us review some examples to understand the above code.  

Case 1

Assume current page = 1, page size = 10 , total item = 160; then total pages to be rendered = Math.ceil(160/10) = 16; since current page = 1, and it has to render a total of 10 pages, so according to the very first condition, that is current page <= 6, follows. This implies start page = 1; end page = 10 

Case 2

Assume current page = 12, page size = 10, total item = 160 ; then total pages to be rendered = Math.ceil(160/10) = 16; since current page = 12, and it still has to render a total of 10 pages, so according to the second condition, that is current page +4 (12+4 = 16) >= total no of pages(16) satisfies, which implies  start page = 16-9 = 7 end page = 16. 

Case 3

Assume current page = 7, page size = 10 , total item = 160; then total pages to be rendered = Math.ceil(160/10) = 16; now current page = 7, and it still has to render total of 10 pages, so according to the third condition, that is current page +4 = (7+4 = 11) < = total no of pages(16), satisfies, which implies start page = 11-5 = 6. React pagination library can be used directly for paging functionality for any list of items. 

The required props here are an array of items of the list to be rendered and a callback function onChange, which informs the parent component about the page change. The default value for the current page is 1, items per page are 10, and the page range to be displayed is 5. There are a lot of other packages available which you can use as per your requirements. For example, end page = 11+ 4 = 15 React.js pagination library can be used directly for paging functionality for any list of items. 

The required props here are an array of items of the list to be rendered and a callback function onChange which informs the parent component about the page change. The default value for the current page is 1, items per page are 10, and the page range to be displayed is 5. A react component using a pagination component. Also, the following code is taken from official NPM documentation of react-pagination. For more details, please refer to react-js-pagination.  

JavaScript
 




xxxxxxxxxx
1
30


 
1
import React, { Component } from "react"; 
2
importReactDOMfrom"react-dom"; 
3
importPaginationfrom"react-js-pagination"; 
4
require("bootstrap/less/bootstrap.less"); 
5
class App extends Component { 
6
constructor(props) { 
7
super(props); 
8
this.state= { 
9
     activePage:15 
10
   }; 
11
 } 
12
handlePageChange(pageNumber) { 
13
   console.log(`active page is ${pageNumber}`); 
14
this.setState({activePage: pageNumber}); 
15
 } 
16
render() { 
17
return ( 
18
<div> 
19
<Pagination 
20
         activePage={this.state.activePage} 
21
         itemsCountPerPage={10} 
22
         totalItemsCount={450} 
23
         pageRangeDisplayed={5} 
24
         onChange={::this.handlePageChange} 
25
/> 
26
</div> 
27
   ); 
28
 } 
29
} 
30
ReactDOM.render(<App />, document.getElementById("root"));



There are many other packages available that you can use according to your requirements, and you can customize it too. If you have any doubts, feel free to ask questions in the comment section. Thank you! 
  • Color Space Image Processing (explained with RGB, CMY, HSI, Color Models) 2020
  • React.js Pagination: How Do You Page Your Data With React.js Pagination?
  • HTML to PDF JavaScript: Export HTML/CSS to PDF Using JavaScript
  • How do you upload and save an Image to Node.js and Express.js using JavaScript?
  • How to Develop a Chat System Design like Facebook Messenger | Whatsapp
  • Browser push notifications using JavaScript
  • What is a hospital management system? Including features and modules | uses -blog
  • How is Diff Algorithm implemented in React.js?
Data (computing)

Published at DZone with permission of sasi kiran. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  • Data Contracts as the "Circuit Breaker" for Model Reliability
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook