🎁 The Js-Craft Guide to React is now available with a 30% off discount!

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 ahead, 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.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.


Leave a Reply

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

📘 The Guide to React Home Screencasts Best of Newsletter Search X

📘 - 10 Javascript AI projects with React and LangChain

Hi friend! Before you go, just wanted to let you know about the 10 Javascript AI projects ideas with React and LangChain FREE ebook.

One of the best ways to learn is by doing the work. Choose from these 10 project ideas and start working on topics such as:

  • How does LangChain work
  • Connecting to OpenAI LLM
  • Create AI Agents
  • Simple and Sequential Chains
  • Adding Memory (Chat Context)
  • Prompt Templates
  • Using OutputParsers and Tools for Agents
  • Work with Documents and more...

Keep building and see the new capabilities LLM models can add to your React app! Get all projects as an ebook right to your inbox!

X