Create Pagination Component for React

Tiempo de lectura: 2 minutos

Today I wanted to share a simple way to implement a pagination component using Material-UI in React. This component is useful when working with extensive lists, allowing navigation between different pages.

First, we create the pagination component with its attributes so we can use it wherever we need it.

import React from 'react';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { primary } from '../../constants/Colors';

interface PaginationProps {
    totalPages: number;
    currentPage: number;
    changePage: (page: number) => void;
}

function PaginationProps({ totalPages, currentPage, changePage }: PaginationProps) {
    const handleChangePage = (event: React.ChangeEvent<unknown>, value: number) => {
        changePage(value);
    };

    const theme = createTheme({
        palette: {
            primary: {
                main: primary,
            },
        },
    });

    return (
        <ThemeProvider theme={theme}>
            <Stack spacing={2}>
                <Pagination
                    count={totalPages}
                    color='primary'
                    size="small"
                    showFirstButton
                    showLastButton
                    onChange={handleChangePage}
                    page={currentPage}
                />
            </Stack>
        </ThemeProvider>
    );
}

export default PaginationProps;

In the above example, we pass the properties expected by the component as parameters.

  • totalPages: Total number of available pages.
  • currentPage: Number of the current page.
  • changePage: Function to be called when the page changes.

Below is an example of implementing the component.

// In your screen or component:

import React, { useState } from 'react';
import PaginationProps from './path/to/component/PaginationProps';

function MyComponent() {
    const [currentPage, setCurrentPage] = useState<number>(1);

    const changePage = (page: number) => {
        setCurrentPage(page);
        // Here you could perform logic to load data for the current page
        // For example, make an API call with the page number
    };

    return (
        <div>
            {/* Other components or elements here */}
            <PaginationProps
                totalPages={10} // Replace with the actual number of pages
                currentPage={currentPage}
                changePage={changePage}
            />
        </div>
    );
}

export default MyComponent;

I hope this helps! Have a great day!!

Leave a Comment