Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to implement pagination in ReactJS

Introduction

When you're just starting out with programming, it's natural to encounter a few challenges that might seem a bit complicated. One of these is pagination. But don't worry, this blog post will simplify it for you. Pagination, similar to flipping through pages in a book, allows you to navigate through different sections of data in your application.

In this guide, we will explore how to implement pagination in ReactJS. ReactJS is a popular JavaScript library used for building user interfaces, especially single-page applications.

What is Pagination?

Imagine you have a book of 200 pages and you want to read from the 150th page. Would you start flipping right from the first page? Of course, not. You'd directly jump to the 150th page. That's exactly what pagination does. It breaks down large amounts of data into manageable chunks or 'pages', enabling users to navigate efficiently through the data.

Why do we need Pagination?

Websites often have to deal with large amounts of data. Presenting all this data at once can overwhelm the user and also strain the system's resources. Pagination helps solve this problem by dividing the data into 'pages' which can be loaded and displayed as required. This leads to a better user experience and efficient resource utilization.

Setting Up Your React App

Before we dive into pagination, let's set up a simple React App. We'll use Create React App (CRA), a handy tool provided by Facebook to bootstrap a React application.

First, install Node.js and npm (Node Package Manager) if you haven't already. Node.js is a JavaScript runtime that allows us to run JavaScript on our servers. npm is a package manager that comes with Node.js and it will help us manage our dependencies.

After installing Node.js and npm, create a new project using CRA by running the following command in your terminal:

npx create-react-app pagination-app

This command will create a new React application named "pagination-app".

Getting Started with Pagination

Let's start by understanding the basic concept. Suppose we have an array of 100 items and we want to display 10 items per page. This means we will have 10 pages.

When the user clicks on a page number, we need to calculate the starting index and the ending index of the items we want to display. Here's how we can do it:

let itemsPerPage = 10;
let pageNumber = 1; // let's say

let startIndex = (pageNumber - 1) * itemsPerPage;
let endIndex = pageNumber * itemsPerPage;

If pageNumber is 1, then startIndex will be 0 and endIndex will be 10. So, for the first page, we will display items from index 0 to 10 from our array. For the second page, we will display items from index 10 to 20, and so on.

Creating the Pagination Component

Now, let's create a simple Pagination Component. This component will display the page numbers and handle the page click events.

import React from 'react';

const Pagination = ({ itemsPerPage, totalItems, paginate }) => {
    const pageNumbers = [];

    for (let i = 1; i <= Math.ceil(totalItems / itemsPerPage); i++) {
        pageNumbers.push(i);
    }

    return (
        <nav>
            <ul className='pagination'>
                {pageNumbers.map(number => (
                    <li key={number} className='page-item'>
                        <a onClick={() => paginate(number)} href='!#' className='page-link'>
                            {number}
                        </a>
                    </li>
                ))}
            </ul>
        </nav>
    );
};

export default Pagination;

In this component, we're calculating the total number of pages and creating an array of page numbers. We're then rendering these page numbers. When a page number is clicked, we call the paginate function passed as a prop to this component with the clicked page number.

Displaying Paginated Data

Now, let's use this Pagination Component to display paginated data in our App Component.

First, let's create some dummy data:

const data = Array.from({length: 100}, (_, i) => i + 1);

This will create an array of numbers from 1 to 100.

Then, import the Pagination Component in our App Component:

import Pagination from './Pagination';

In our App Component state, let's add two new fields - currentPage and itemsPerPage.

this.state = {
    data: Array.from({length: 100}, (_, i) => i + 1),
    currentPage: 1,
    itemsPerPage: 10
};

Now, in our render method, let's calculate the data for the current page:

const { data, currentPage, itemsPerPage } = this.state;

const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);

Finally, let's render our data and the Pagination Component:

return (
    <div>
        {currentItems.map(item => <h2>{item}</h2>)}

        <Pagination 
            itemsPerPage={itemsPerPage}
            totalItems={data.length}
            paginate={this.paginate}
        />
    </div>
);

The paginate function is a method in our App Component which updates the currentPage in our state:

paginate = pageNumber => this.setState({ currentPage: pageNumber });

And that's it! You have successfully implemented pagination in your ReactJS application.

Wrapping up

Pagination is an essential feature for handling large sets of data in a way that enhances user experience and optimises system performance. In this blog post, we have managed to demystify the concept of pagination and have successfully implemented it in ReactJS. As a budding programmer, understanding these concepts will prove invaluable as you progress and tackle more complex tasks. Happy coding!