React Pagination Component
Pagination is simple and repeatable, let’s make it a component!
Limit Your API Requests
It’s important to limit the amount of data queried by your API in a single request, especially if you’re not using a caching mechanism. There are a lot of alternatives to implement pagination on your server, but that’s not what this article is about.
Pagination Schema
Let’s pretend we’re querying for a list of Posts. Alongside the Posts, we get back a few pieces of pagination data. Let’s assume the pagination schema is as follows:
{
total_pages: 4, // the number of pages of data
current_page: 1, // the current page being queried
total_count: 39, // the total number of documents
max_per_page: 10, // the number of documents returned per page
}With that schema, we can design a React component that expects that data and renders “Next” or “Previous” buttons. We’ll be using the Bootstrap pagination classes to make it look good! We’re going to write this component as purely functional because it doesn’t need any logic! Let’s see how:
// Pagination.jsximport React from 'react';
import PropTypes from 'prop-types';const Pagination = ({ onPageRequest, pagination }) => {// If the back button should be enabled
const allowPrevious = pagination.current_page !== 1;// If the next button should be enabled
const allowNext = pagination.current_page !== total_pages;// If we're on the first page
const firstPage = pagination.current_page === 1;// If we're on the last page
const finalPage = current_page === total_pages;// The index of the previous page
const previousPage = current_page - 1;// The index of the next page
const nextPage = current_page + 1;return (
<ul className="pager">
<li onClick={allowPrevious && onPageRequest(previousPage)}>
<a>← Previous</a>
</li>
<li>
<div
className="inline-block"
>
Displaying Results
{firstPage ?
1 :
previousPage * max_per_page
}
to
{finalPage ?
total_count :
current_page * max_per_page
}
<strong>Total Results: {total_count}</strong>
</div>
</li>
<li onClick={allowNext && onPageRequest(nextPage)}>
<a>Next →</a>
</li>
</ul>
);
}Pagination.propTypes = {
onPageRequest: PropTypes.func.isRequired,
pagination: PropTypes.shape({
total_pages: PropTypes.number.isRequired,
current_page: PropTypes.number.isRequired,
total_count: PropTypes.number.isRequired,
max_per_page: PropTypes.number.isRequired,
}),
};
How ‘bout them apples! Just like that, anytime you make a paginated request, you can automatically place a cute looking pagination component at the end of the list! At the very end you can expect to find something that looks a little like this:

Happy coding!

