Simple Pagination in React.js App

    May 25, 2017       by Suraj Roy
simple-pagination.jpg

Today I will explain to create a demo of simple pagination in React.js App. 

 

Here in this demo we will create-react-app tool for creating the application. For creating basic app in react see my previous demo

I am assuming that everything is installed and you have created a basic react app and run it over browser. Now let's move to the pagination part.

 

Create Pagination Component

In the src folder, We will create a folder named components where we will write code for pagination. In this folder, Firstly we will create pagination component, It will be a self-contained reusable component that can be used for paging for any kind of list. It will take an array for showing pagination and an onChangePage() callback function to notify the parent component when the page moved to previous or next pages.

So create a file named pagination.js and put the below code in this file:

 

 
import React from 'react';
import PropTypes from 'prop-types';
 
const propTypes = {
items: PropTypes.array.isRequired,
onChangePage: PropTypes.func.isRequired,
initialPage: PropTypes.number,
pageSize: PropTypes.number
}
 
const defaultProps = {
initialPage: 1,
pageSize: 10
}
 
class Pagination extends React.Component {
constructor(props) {
super(props);
this.state = { pager: {} };
}
 
componentWillMount() {
// set page if items array isn't empty
if (this.props.items && this.props.items.length) {
this.setPage(this.props.initialPage);
}
}
 
componentDidUpdate(prevProps, prevState) {
// reset page if items array has changed
if (this.props.items !== prevProps.items) {
this.setPage(this.props.initialPage);
}
}
 
setPage(page) {
var { items, pageSize } = this.props;
var pager = this.state.pager;
 
if (page < 1 || page > pager.totalPages) {
return;
}
 
// get new pager object for specified page
pager = this.getPager(items.length, page, pageSize);
 
// get new page of items from items array
var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
 
// update state
this.setState({ pager: pager });
 
// call change page function in parent component
this.props.onChangePage(pageOfItems);
}
 
getPager(totalItems, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
 
// default page size is 10
pageSize = pageSize || 10;
 
// calculate total pages
var totalPages = Math.ceil(totalItems / pageSize);
 
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
 
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
 
// create an array of pages to ng-repeat in the pager control
var pages = [...Array((endPage + 1) - startPage).keys()].map(i => startPage + i);
 
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
 
render() {
var pager = this.state.pager;
 
if (!pager.pages || pager.pages.length <= 1) {
// don't display pager if there is only 1 page
return null;
}
 
return (
<ul className="pagination">
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(1)}>First</a>
</li>
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
</li>
{pager.pages.map((page, index) =>
<li key={index} className={pager.currentPage === page ? 'active' : ''}>
<a onClick={() => this.setPage(page)}>{page}</a>
</li>
)}
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
</li>
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.totalPages)}>Last</a>
</li>
</ul>
);
}
}
 
Pagination.propTypes = propTypes;
Pagination.defaultProps = defaultProps;
export default Pagination;
 

 

Create Main  Component

 

Under that folder we will create a file called App.js file where we will create dummy data and will map it with html element and also render it. So copy the code below and paste it in App.js file

 

 
import React from 'react';
import Pagination from './Pagination';
 
class App extends React.Component {
constructor() {
super();
 
// an example array of items to be paged
var exampleItems = [...Array(150).keys()].map(i => ({ id: (i+1), name: 'list item ' + (i+1) }));
 
this.state = {
exampleItems: exampleItems,
pageOfItems: []
};
this.onChangePage = this.onChangePage.bind(this);
}
 
onChangePage(pageOfItems) {
// update state with new page of items
this.setState({ pageOfItems: pageOfItems });
}
 
render() {
return (
<div>
<div className="container">
<div className="text-center">
<h1>React Simple Pagination</h1>
{this.state.pageOfItems.map(item =>
<div key={item.id}>{item.name}</div>
)}
<Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
</div>
</div>
</div>
);
}
}
 
export default App;
 

 

Now we will update the index.js file in src folder. Update it with below code:

 

 
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
 
ReactDOM.render(<App />, document.getElementById('root'));
 

 

Now run the app over terminal and check the over browser at link http://localhost:3000. The page will look like below:

pagination image

Conclusion

 

So in this demo, We  learnt how to create simple pagination in React.js application. Find here other React.js sample projects

 

That’s all for now. Thank you for reading and I hope this demo will be very helpful for simple pagination in React.js App.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


Find other similar Articles here: