How to Implement Numerical Pagination in React with Mantine UI: A Step-by-Step Guide

Photo by Goran Ivos on Unsplash

How to Implement Numerical Pagination in React with Mantine UI: A Step-by-Step Guide

Introduction

When you're working with large datasets, it can pose a challenge to display all the data on a single page without causing it to become sluggish or unresponsive. That's where pagination comes into play. Pagination is the technique of breaking down a sizable dataset into smaller, more manageable pages. This approach enables users to view the data in bite-sized portions, leading to a better overall user experience.

There are several pagination techniques that are usually found on web applications. These techniques offer different ways of navigating and accessing the data in a convenient manner.

  1. Numeric Pagination:

Numeric pagination is one of the most straightforward and widely used pagination methods. It involves displaying a series of page numbers, thus allowing users to navigate to specific pages directly. For instance, the pagination button can show page numbers like "1, 2, 3, 4, 5, ..." with clickable links to each specific page.For instance, when you are on an e-commerce website, you might see a list of products divided into multiple pages or sorted according to the product categories. Then, at the bottom, there could be a pagination bar displaying page numbers for users to jump to a particular page of products.

2. Load More Pagination:

Load more pagination, also known as "infinite scroll". Load more enables lazy loading, and only provides select datasets depending on the current view of the user. This offers a seamless scrolling experience by dynamically loading additional content as the user reaches the end of the current page. So, instead of traditional pagination links or buttons, new data is loaded automatically without requiring explicit user action on the website as they scroll the website.This is mostly found on Social media platforms like Facebook, Reddit and Twitter, where new posts or tweets continuously load as the user scrolls down the page.

3. Previous/Next Pagination:

This pagination method includes previous and next navigation links to move between pages. It provides the option to move forward to the next page or backward to the previous page, making it easy for users to browse through the content sequentially as needed. For instance: News websites often utilize previous/next pagination to allow readers to navigate through articles one at a time.

4. Alphabetical Pagination:

Alphabetical pagination is useful when dealing with large sets of data that can be sorted alphabetically. It presents a list of clickable letters or alphabetical ranges, allowing users to filter and navigate the data based on the selected letter.Example: A directory website may use alphabetical pagination to help users find contacts or listings by selecting a specific letter on the page.

Why use pagination on websites?

Each pagination type serves a different purpose and caters to specific use cases. Implementing pagination is crucial as it allows for better navigation and thus prompting a more intuitive user experience on the website. This is done by dividing the available datasets into smaller chunks or pages. Doing this allows users to easily browse through the content without being overwhelmed in the process.

Suppose you are developing an e-commerce website with a large product catalog. In that case, implementing pagination becomes even more critical as it enables users to browse through different pages of products, making their shopping experience more manageable.

So, in this article, you will learn how to implement the Numerical pagination functionality using Mantine UI.

What is Mantine UI?

Mantine UI is a user-friendly and highly accessible UI library that aims to simplify the web development process. It has a wide range of built-in components and easy customization options which is advantageous for developers to incorporate on their webapps.

Why use Mantine UI?

  1. One of the key reasons to consider using Mantine UI is its flexibility. The library provides a comprehensive set of pre-built components that can be easily incorporated into your web application. Additionally, Mantine UI offers hooks and APIs that allow for in-depth customization, which will enable you to tailor the components to meet your specific needs. This flexibility ensures that you can create unique and visually appealing interfaces that align with your design vision as opposed to being similar to other webapps.

  2. Another notable advantage of Mantine UI is its smaller size compared to other UI libraries. This reduced size is due to its modular structure, which allows developers to selectively install only the required packages of the library that they need in their projects. For instance, you can decide to install the @mantine/dates packages when it’s needed or the modal package @mantine/modal on your application. So, with the absence of unnecessary dependencies, Mantine UI optimizes the bundle size of the application and thus improves the overall performance of your web application. This lightweight approach ensures faster loading times and a smoother user experience, especially in situations where bandwidth or device resources may be limited.

  3. Mantine UI significantly simplifies the development process by handling many design-related tasks. With its extensive collection of pre-styled components, you can save time and effort that would otherwise be spent on designing and styling from scratch. This streamlined approach allows developers to focus more on building the functionality of their websites rather than getting caught up in the intricacies of UI design.

With the above in mind, this tutorial will describe how you can implement the numerical pagination using Mantine UI. The approach Mantine UI implements for pagination is with the Pagination component and the usePagination hook which are already inbuilt in the Mantine UI library. Therefore, Mantine UI not only provides an easy way to navigate pagination with fewer lines of code but also ensures visually appealing designs for your dataset.

Prerequisites
1. Have npm installed
2. Have basic knowledge of react

Step 1. Install React on your system.

You can either use create-react-app or vite for this project

Step 2: Install mantine UI.

Mantine UI allows developers to choose the dependencies needed in the application. So, for this tutorial, we only need the mantine/core and the mantine/hooks to get started. So, you can run these commands on your terminal to install the mantine packages needed for this tutorial

npm install @mantine/core @mantine/hooks @emotion/react

Step 3: Wrap your application with MantineProvider

In the index.js/main.js file of your React application, import the MantineProvider from @mantine/core and wrap your application with it. This allows you to use Mantine UI components throughout your application.

Code example

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import { MantineProvider } from "@mantine/core";

ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
    <MantineProvider withGlobalStyles withNormalizeCSS>
        <App />
    </MantineProvider>
</React.StrictMode>
);

Step 4: Implement Numerical Pagination using Mantine UI

Import components and create App component

In the App.js file of your react application, import the necessary Mantine UI components. For the mockData, I created a dummy data array, which you can access here in the repository here.

import { Group, Pagination, Stack, Text, Title } from "@mantine/core";
import { useState } from "react";

import { mockData } from "./data";

function App() {

...

}

{ // ... }

This step involves creating the App functional component that represents the pagination feature.

Declaring Variables


import { Group, Pagination, Stack, Text, Title } from "@mantine/core";
import { useState } from "react";
import { mockData } from "./data";

function App() {
const pageSize = 5;
const [pageNumber, setPageNumber] = useState(1); 
}

Within the AppComponent, declare two variables:

  • pageSize: This constant variable determines the number of items to display per page. It is set to 5.

  • pageNumber and setPageNumber: These are derived from the useState hook. pageNumber is a state variable initialized with 1, and setPageNumber is a function to update the pageNumber state.

Calculating Page Data

const startingIndex = (pageNumber - 1) * pageSize;
const pageData = mockData.slice(startingIndex, startingIndex + pageSize);
  • In this step, we calculate the starting index of the current page using the formula (pageNumber - 1) * pageSize. It represents the index of the first item on the current page.

  • We then create a new array pageData by extracting a portion of the mockData array using the slice method. The extracted portion starts from the startingIndex and includes pageSize number of items. This array contains the data to be displayed on the current page.

Handling Page Change

const handlePageChange = (newPage) => {
    setPageNumber(newPage);
  };
  • This step involves defining a function handlePageChange that takes a newPage parameter.

  • Inside the function, we call the setPageNumber function to update the pageNumber state with the value of newPage.

  • This function will be used to handle page change events triggered by the Pagination component.

Rendering JSX Markup

return (
    <Stack spacing="xs">
        <Title>Learning Pagination</Title>
        <Group>
            <Text weight={500}>First Name</Text>
            <Text weight={500}>Last Name</Text>
            <Text weight={500}>Year</Text>
        </Group>
    {pageData.map((data) => (
          <Group key={data.id}>
            <Text>{data.firstName}</Text>
            <Text>{data.lastName}</Text>
            <Text>{data.yearOfBirth}</Text>
          </Group>
      ))}
    <Pagination
        total={Math.ceil(mockData.length / pageSize)}
        withEdges
        page={pageNumber}
        onChange={handlePageChange}
        styles={() => ({item: {
                            background: "none",
                            border: "1px solid gray",
                                },
                        })}
       />
    </Stack>);
  • This step involves returning the JSX markup to be rendered as the output of the App component.

  • We use a Stack component to control the spacing between elements.

  • We render a Title component with the text "Learning Pagination" as the title of the pagination feature.

  • A Group component is used to display the column headers: "First Name", "Last Name", and "Year". These headers are represented by Text components with a weight of 500.

  • We use the map function on the pageData array to iterate over each data item and render a Group component for each item. Inside each Group, we display the first name, last name, and year of birth using Text components.

  • The Pagination component is rendered to display the pagination buttons. It receives several props, including:

  • total: Calculated by dividing the length of the mockData array by pageSize and rounding up using Math.ceil. It represents the total number of pages needed to display all the data items.

  • withEdges: A boolean prop that determines whether the pagination should show the first and last page buttons.

  • page: Set to the current pageNumber state.

  • onChange: Set to the handlePageChange function, which will be called when the page is changed.

  • styles: A function that returns an object with custom styles for the pagination items. In this case, it sets the background to "none" and the border to "1px solid gray".

Exporting the App Component

export default App;
  • This exports the App component as the default export of the module, making it available for use in other parts of the application.

The implementation should look like this video and here is the link to the repository.

As can be seen in the video, Mantine UI allows for the combination of using the Numeric pagination and the Previous/Next pagination methods with fewer lines of code. This allows the user to navigate between pages, skip to the first/last pages and render the corresponding data for each page.

Conclusion

Mantine UI enables developers to focus on delivering robust and feature-rich web applications by handling the visual elements effectively As can be seen with our implementation above, the pagination tabs are already built-in and ready for use. The customization helps to provide unique designs, while also simplifying the development process and thus allows you to focus on building the core functionality of your website, in this case, the pagination implementation. The above makes Mantine UI an excellent choice when you are seeking an efficient and customizable method to implement certain features like pagination in your web applications.