Paginate an array of objects in React

After publishing the NextJs 13 pagination example with useInfiniteQuery() I've got an email asking how can we implement client side pagination for a very long array of objects in React.

Let's say that we receive an array with a few hundred entries and we want to use React to paginate this data on the client side and show it in a table.

And we want to wrap it all in a usePagination() hook:
Paginate an array of objects in React

If you want to skip you can play with the live example here, and here is the GitHub repo.

Generating the data array

We will start by generating some test data:

const array = Array.from(
    {length: 48}, () => ({
        id: Math.floor(Math.random() * 1024), 
        salary: Math.floor(Math.random() * 40)
    })
);

The below code will produce an array of random objects with the following format:

[ {id: 123, salary: 12}, {id: 456, salary: 34} ... }

Making the usePagination() React hook

Now for the magic part let's implement the usePagination() hook. It will take the following parameters:

  • items all data array that needs to be paginated
  • page the currently active page; by default, we start from the first page
  • perPage how many items we want to have per page; defaults to 10

Below is the implementation:

const usePagination = (items, page = 1, perPage = 10) => {
    const [activePage, setActivePage] = useState(page)
    const totalPages = Math.ceil(items.length / perPage)
    const offset = perPage * (activePage - 1)
    const paginatedItems = items.slice(offset, perPage * activePage)

    return {
        activePage,
        nextPage: ()=> setActivePage(p => p < totalPages ? p + 1 : p),
        previousPage: ()=> setActivePage(p => p > 1 ? p - 1 : p),
        totalPages,
        totalItems: items.length,
        items: paginatedItems,
    }
}

The usePagination() hook us will give us back the following data:

  • activePage is the index of the currently active page
  • nextPage, previousPage functions that control the activePage
  • totalPages how many pages of data we have
  • items an array with the items for the active page

Example usage:

const { activePage, nextPage, previousPage, totalPages, totalItems, items } = usePagination(array);

Displaying the usePagination() data in a table

And finally, we can take the data, paginate it using the hook and display it in a table with the corresponding page controls:

const App = () => {
    const { activePage, nextPage, previousPage, totalPages, totalItems, items } = usePagination(array);

    return <div>
        <h1>Static array paginated in React</h1>
        <table>
            <thead><tr>
                <th>🙂 User ID</th>
                <th>💰 Salary</th>
            </tr></thead>
            <tbody>
                {items.map( (item, i) => <tr key={i}>
                    <td>{item.id}</td>
                    <td>{item.salary}</td>
                </tr>)}
            </tbody>
        </table>
    {/* Control bar for the page data */}
        <p>
            <button onClick={previousPage}
                disabled={activePage <= 1}>
                Previous
            </button>
            <button onClick={nextPage}
                disabled={activePage >= totalPages}>
                Next</button>
            <em>(page {activePage}/{totalPages})</em>
        </p>
    </div>
}

And there you have it! The full code is here and the live example here.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X