Front-end Pagination with React

Nick Repasy
2 min readJul 12, 2021

Last month I was working on a project that allowed users to access the MET Museum’s API to search for any artwork in their collection. To my frustration their API was not set up to allow for pagination when making requests, which led to issues if a user was using more “generic” queries in their searches. More detailed searches would return only a small number of results, but say for instance someone searched for “clay” the request could receive potentially thousands of results, which would result in too many requests being made from the server, and ultimately it would time out.

Only recently, I discovered react has a pagination hook that can be installed in the same way as useEffect, or useState. Here is a quick guide on the use of that hook.

The first step is to install it as you would any other react hook.

npm install react-paginate --save

And then in whichever component you’re deploying it in.

import ReactPaginate from 'react-paginate';

From there, ReactPaginate has it’s own set of props that are used to flesh out your results and how they are paginated.

https://www.npmjs.com/package/react-paginate
https://www.npmjs.com/package/react-paginate
return (
<div>
<label>Search</label>
<input type="text" onChange={(event) => setQuery(event.target.value)} />
<button onClick={handleFetch}>Get Data</button>

{isLoaded ? (
hits.map((item) => {
return (
<NewsCard
url={item.url}
title={item.title}
author={item.author}
key={item.objectID}
/>
);})
) : (
<div></div>
)}
#New
{isLoaded ? (
<ReactPaginate
pageCount={pageCount}
pageRange={2}
marginPagesDisplayed={2}
onPageChange={handlePageChange}
containerClassName={'container'}
previousLinkClassName={'page'}
breakClassName={'page'}
nextLinkClassName={'page'}
pageClassName={'page'}
disabledClassName={'disabled'}
activeClassName={'active'}
/>
) : (
<div>Nothing to display</div>
)}

</div>);

--

--