Implementing Pagination in React: Exploring a Custom Pagination Hook

in blurt •  2 years ago 

Introduction:

📚 Pagination is a common feature in web applications. ANd This involves dividing large amounts of data into smaller. In this article, we will explore how to implement pagination in a React application. By using a customized pagination hook. We will review the code example provided. Let's get started!

src

Code Explanation:

The code provided consists of two parts: a custom pagination hook and its usage in another file. Let's break it down step by step:

Custom Pagination Hook:

import { useMemo } from 'react';

export const DOTS = '...';

const range = (start, end) => {
    let length = end - start + 1;
    return Array.from({ length }, (_, idx) => idx + start);
};

export const usePagination = ({
    totalCount,
    pageSize,
    siblingCount = 1,
    currentPage
}) => {
    const paginationRange = useMemo(() => {
        // Calculate total page count
        const totalPageCount = Math.ceil(totalCount / pageSize);

        // Determine the number of page numbers to be displayed
        const totalPageNumbers = siblingCount + 5;

        // Handle case when totalPageNumbers >= totalPageCount
        if (totalPageNumbers >= totalPageCount) {
            return range(1, totalPageCount);
        }

        // Calculate left and right sibling indexes
        const leftSiblingIndex = Math.max(currentPage - siblingCount, 1);
        const rightSiblingIndex = Math.min(
            currentPage + siblingCount,
            totalPageCount
        );

        // Determine whether to show dots on the left and right sides
        const shouldShowLeftDots = leftSiblingIndex > 2;
        const shouldShowRightDots = rightSiblingIndex < totalPageCount - 2;

        // Generate pagination range based on conditions
        if (!shouldShowLeftDots && shouldShowRightDots) {
            let leftItemCount = 3 + 2 * siblingCount;
            let leftRange = range(1, leftItemCount);
            return [...leftRange, DOTS, totalPageCount];
        }

        if (shouldShowLeftDots && !shouldShowRightDots) {
            let rightItemCount = 3 + 2 * siblingCount;
            let rightRange = range(
                totalPageCount - rightItemCount + 1,
                totalPageCount
            );
            return [1, DOTS, ...rightRange];
        }

        if (shouldShowLeftDots && shouldShowRightDots) {
            let middleRange = range(leftSiblingIndex, rightSiblingIndex);
            return [1, DOTS, ...middleRange, DOTS, totalPageCount];
        }
    }, [totalCount, pageSize, siblingCount, currentPage]);

    return paginationRange;
};


src
Calculating the Pagination Range:
The custom hook, usePagination, is implemented using React's useMemo hook. It takes an object with four properties: totalCount, pageSize, siblingCount, and currentPage. Here's a breakdown of what each property represents:
totalCount: The total number of items to be paginated.
pageSize: The number of items to be displayed per page.
siblingCount: The number of page numbers to be displayed on each side of the current page.
currentPage: The current active page number.
Inside the usePagination hook, a paginationRange variable is calculated using the useMemo hook. The paginationRange represents the range of page numbers to be displayed in the pagination component.

src
Range Calculation and Handling Dots:
The range function is a helper function that generates an array of numbers within a given range. The DOTS constant represents the dots (...) placeholder.
The paginationRange is determined based on several conditions and requirements:

Total Page Count: The totalPageCount is calculated by dividing the totalCount by the pageSize. And then also rounding up using Math.ceil. This determines the total number of pages needed to display all the items.

Total Page Numbers: The totalPageNumbers variable is set to the sum of siblingCount (pages on each side of the current page), 5 (1 for the first page, 1 for the last page, 1 for the current page, and 2 for the dots).

Handling Fewer Pages: If the total number of pages is less than or equal to the totalPageNumbers, the range is set to include all the pages from 1 to totalPageCount.

Handling Dots: The code then checks if the dots should be shown on the left side, right side, or both sides of the pagination range. It determines the leftSiblingIndex and rightSiblingIndex based on the current page and the siblingCount.

Generating the Range: Depending on the conditions, the appropriate range is generated using the range function.

src
Returning the Pagination Range: Finally, the paginationRange array is returned, representing the range of page numbers to be displayed in the pagination component.

Conclusion:

🎉 In this blog post, we explored a code snippet that demonstrates the implementation of pagination using React and a custom pagination hook. We went through the code step by step, explaining its purpose and functionality. Understanding this code can help developers incorporate pagination into their React applications efficiently. By leveraging custom hooks and React's built-in functionality, we can create flexible and user-friendly pagination components. Happy coding! 😊

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!