How to Implement Pagination in your React.js?

How to Implement Pagination in your React.js?

Dhaval Baldha

08 Jan 2024

6 MINUTES READ

Introduction

Every business aims to develop a visually appealing and reliable online application. Every element, including navigation, UI/UX design, and page loading speed, must be flawless because your website serves as a channel for communicating with potential customers.

The basic information on your website, which showcases your offerings, and all the information you need to produce and add detailed content for each component that could turn a visitor into a possible customer.

Both the customer and the developer may find this to be a tedious effort. Every customer would dislike a clustered website with various navigation options.

To eliminate this task the term pagination is used that divide the code into discrete pages which enhances the user experience by making the data more efficient.

What is Pagination in React.js

In simple terms, pagination in react .js can be referred to as a process of dividing web content into discrete pages that enhance the user experience for your website by making data management more efficient.

If we look further pagination plays a vital role as the practice of breaking down the content into various pages offer

  • Faster Load times: It reduces the initial load time of the webpage as it loads a specific number of pages at a time.
  • Improved User Experience: Making it easy to navigate through lengthy content.
  • Easier Navigation: It simplifies the user to find specific items within a large set of data or content.

Pagination Logic

We'll begin by focusing on the App.jsx file within the src directory. This is where the core pagination logic will be implemented. Here are the key steps:

  • Data Storage: Utilize the useState hook to store data fetched from the server. Initialize the state with an empty array.
  • Loading Indicator: Set up a loading state to notify users when data is being fetched. Initialize it as false.
  • Current Page Management: Create a currentPage state to keep track of the currently displayed page. If you're working with 100 items and want to show 10 per page, initialize this state with 1.
  • Posts Per Page: Implement a state to manage the number of posts displayed per page. In this article, we'll consider 10 posts per page.

    useEffect (() => {
        const fetchPosts = async () => {
            setLoading (true);
            try {
                const response = await fetch("https://jsonplaceholder.typicode.com/posts");
                const data = await response.json();
                setPosts (data);
                setLoading (false);
            } catch (error) {
                console.log(error);
            }
        };
        fetchPosts();
    }, []);          
                    

Fetching Data from the Server

Here's how you can handle the data-fetching process:

  • UseEffect for Fetching: Create a useEffect to fetch data from the API. This ensures that data is fetched when the component mounts.
  • Fetching Function: Inside the useEffect, implement an async function using fetch to retrieve data from the API endpoint.
  • Updating State: Set the post state to the fetched data. Don't forget to handle loading states appropriately.

Displaying Paginated Data

Over here we will create a Post comment. This component will receive the posts array and the loading state as props. Here's how you can structure the Post component:


    import React from 'react';

    const Post = ({ posts, loading }) => {
        if (loading) {
            return <h1>Loading...</h1>;
        }

        return (
            <>
                {posts.map((data, index) => (
                <div className='list' key={index}>
                    <p>{data.title}</p>
                </div>
            ))}
        </>
        );
    };

    export default Post;
        

To make it more appealing and attractive you can integrate the CSS coding


    body {
        background: black; color: white;
    }

    .container {
        width: 100%;
        max-width: 800px;
        margin: auto;
    }

    .list {
        border: 1px solid #fff;
        padding: 5px;
    }
        
    .pagination {
        display: flex;
        border: 1px solid #fff;
        justify-content: space-between;
        padding: 20px;
    }

    .pagination button {
        padding: 10px;
    }
        
    .active {
        background: black;
        color: #fff;
        border: 1px solid #fff;
    }
                

Pagination Component

Over here we need to create a Pagination component that will calculate the number of pages based on the data length and posts per page. Here's the process

  • Calculating Pages: Using a loop, determine the number of pages needed based on the data length and posts per page.
  • Rendering Page Numbers: Render buttons with page numbers for navigation. We'll utilize the map function to create buttons for each page.

    import React from 'react';

    const Pagination = ({ postsPerPage, length}) => {
        const paginationNumbers = [];

        for (let i = 1; i <= Math.ceil(length / postsPerPage); i++) {
            paginationNumbers.push(i);
        }

        return (
            <div className='pagination'>
                {paginationNumbers.map((pageNumber) => (
                    <button key={pageNumber}>{pageNumber}</button>
                ))}
            </div>
        );
    };
    export default Pagination;
    

Handling Page Changes

To handle page change you need to make the pagination dynamic. This involves updating the currentPage state. Here's how you can achieve this

  • Creating the Handler: Define a function, such as handlepagination, in your App.jsx to update the currentPage state.
  • Passing the Handler: Pass the handlePagination function to the Pagination component as a prop.
  • Using the Handler: Inside the Pagination component, implement the onClick event for each page button. Call the handlePagination function with the appropriate page number.

    const handlePagination = (pageNumber) => {
        setCurrentPage (pageNumber);
    };

    // Inside your component's return...
    <Pagination
        length={posts.length}
        postsPerPage={postsPerPage}
        handlePagination={handlePagination}
    />
            

Highlighting the Active Page

By highlighting the active page you get a better user experience where you need to add a dynamic class to the active page's button. Here's how:

  • Conditional Class: Inside the Pagination component's map function, conditionally apply a class to the active page's button.

    {paginationNumbers.map((pageNumber) => (
        <button
            key={pageNumber}
            className={currentPage === pageNumber? 'active' : ''}
        >
            {pageNumber}
        </button>
    ))}
        

Types of Web API Pagination

This was a basic pagination for your web application but various types of Web API pagination offer different outcomes for better web performance. So, here we have mentioned some of the web API Pagination which can be the best choice for your next project.

  • Cursor API Pagination

    On using this pagination the server will usually return the element to retrieve the next page. This element is usually hidden, also, so users can’t manipulate the results. Some APIs will send a cursor for each element so that they can link elements together.

    Some APIs return the cursor in the payload. Others will return it as a Header, especially Link Headers. Cursors sometimes contain data that can be used to filter other parameters.

  • Keyset API Pagination

    Keyset-based API pagination is when an API provides a key parameter that delineates the query results. One example is if an API is sorted by ID, one key parameter could be since_id. Some other possibilities could include since_updated_at or since_created_at.

  • Offset API Pagination

    It’s one of the most common forms of API pagination, particularly if you’re using a SQL database. It’s also sometimes called page-based pagination. An API endpoint accepts a parameter for a page number and then returns that page.

Conclusion

Consequently, the conclusion makes it quite evident that pagination must be included in your react.js application. So, now if you are willing to implement API pagination in your react.js app the Techvoot Solution is the word.

As IT developers, it’s important to keep these considerations in mind as well. We ensure that your customers and API consumers get the best possible service and results while creating your API pagination.

FAQ

Pagination significantly improves user experience by reducing page load times and presenting data in manageable chunks, preventing information overload.

Yes, using dedicated pagination libraries streamlines the process and ensures a more robust solution with fewer development efforts.

Factors such as ease of integration, customization options, community support, and compatibility with your project requirements.

Optimize performance by minimizing unnecessary re-renders, utilizing virtualization techniques, and implementing server-side pagination for extensive datasets.

Dynamic data handling requires careful consideration of state management. Ensure your pagination system accommodates changes in data dynamically.

Dhaval Baldha
Dhaval Baldha

Co-founder

Dhaval is a visionary leader driving technological innovation and excellence. With a keen strategic mindset and deep industry expertise, he propels the company towards new heights. His leadership and passion for technology make him a cornerstone of Techvoot Solutions' success.

Linkedin
Hire Skilled Developer

*Please fill all the required fields

Get our Newsletter

Customized solutions for your projects

*Please fill all the required fields