,

React 18 : Server-side Table Pagination with React-Bootstrap

In this tutorial, we will be discussing how to create a fully functional pagination system using React.js. Pagination is a crucial aspect of any application that deals with a large amount of data, as it allows users to navigate through and access the information they need easily. Our pagination system will include features such as…

By.

min read

In this tutorial, we will be discussing how to create a fully functional pagination system using React.js. Pagination is a crucial aspect of any application that deals with a large amount of data, as it allows users to navigate through and access the information they need easily. Our pagination system will include features such as the ability to navigate to specific pages and first, last, next, and previous buttons for easy navigation. Additionally, we will also be implementing a server-side pagination system to fetch only the current page’s data from the server, rather than loading all data at once.

The first step in creating our pagination system will be to set up our data table component, which will display the data to the user. We will be using the react-bootstrap library to style and format our table. Next, we will create a custom pagination component that will handle the logic and functionality of our pagination system. This component will allow the user to navigate to specific pages and provide first, last, next, and previous buttons for easy navigation.

Finally, we will implement a server-side pagination system to fetch only the current page’s data from the server, rather than loading all data at once. This will greatly improve the performance of our application and provide a smoother experience for the user. By the end of this tutorial, you will have a fully functional pagination system that is both user-friendly and efficient.

 

Step 1: Create a data table component

We will start by creating a data table component that will display the data in a tabular format. This component will take the data as a prop and display it in a table.

Create a new file DataTable.jsx and import the react-bootstrap Table component and Spinner component. We will display a snipper until the data is shown to the user.

import React, { useState, useEffect } from "react";
import { Table, Spinner } from "react-bootstrap";
import axios from "axios";
import CustomPagination from "./Pagination";

const DataTable = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [dataPerPage] = useState(10);

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `http://localhost:40000/data?page=${currentPage}&per_page=${dataPerPage}`
      );
      setData(result.data);
      // const response = await fetch(
      //   `http://4000/data?page=${currentPage}&per_page=${dataPerPage}`
      // );
      // const data = await response.json();
      setLoading(false);
    };
    fetchData();
    // }, []);
  }, [currentPage, dataPerPage]);

  // Get current data
  const indexOfLastData = currentPage * dataPerPage;
  const indexOfFirstData = indexOfLastData - dataPerPage;
  const currentData = data.slice(indexOfFirstData, indexOfLastData);

  // Change page
  const paginate = (pageNumber) => setCurrentPage(pageNumber);

  return (
    <div>
      {loading ? (
        <Spinner animation="border" variant="primary" />
      ) : (
        <>
          <Table striped bordered hover>
            <thead>
              <tr>
                <th>#</th>
                <th>Name</th>
                <th>Age</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody>
              {currentData.map((item, index) => (
                <tr key={item.id}>
                  <td>{index + 1}</td>
                  <td>{item.name}</td>
                  <td>{item.age}</td>
                  <td>{item.email}</td>
                </tr>
              ))}
            </tbody>
          </Table>
          <CustomPagination
            dataPerPage={dataPerPage}
            totalData={data.length}
            paginate={paginate}
            currentPage={currentPage}
          />
        </>
      )}
    </div>
  );
};

export default DataTable;

 

Step 2: Create a pagination component

Next, we will create a custom pagination component that will allow users to navigate through the data. This component will take the total number of data, data per page, and a paginate function as props. The paginate function will be used to update the current page when a user clicks on a page number.

Create a new file CustomPagination.jsx and update with following code:

import React from "react";
import Pagination from "react-bootstrap/Pagination";

const CustomPagination = ({
  dataPerPage,
  totalData,
  paginate,
  currentPage,
}) => {
  const pageNumbers = [];

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

  let start = 1,
    end = pageNumbers.length;
  if (currentPage - 2 > 1) {
    start = currentPage - 2;
  }
  if (currentPage + 2 < pageNumbers.length) {
    end = currentPage + 2;
  }

  return (
    <Pagination>
      <Pagination.First
        onClick={() => paginate(1)}
        disabled={currentPage === 1}
      />
      <Pagination.Prev
        onClick={() => paginate(currentPage - 1)}
        disabled={currentPage === 1}
      />
      {start !== 1 && <Pagination.Ellipsis />}
      {pageNumbers.slice(start - 1, end).map((number) => (
        <Pagination.Item
          key={number}
          onClick={() => paginate(number)}
          active={currentPage === number}
        >
          {number}
        </Pagination.Item>
      ))}
      {end !== pageNumbers.length && <Pagination.Ellipsis />}
      <Pagination.Next
        onClick={() => paginate(currentPage + 1)}
        disabled={currentPage === pageNumbers.length}
      />
      <Pagination.Last
        onClick={() => paginate(pageNumbers.length)}
        disabled={currentPage === pageNumbers.length}
      />
    </Pagination>
  );
};

export default CustomPagination;

We have used react-bootstrap Pagination components to create a customer styles pagination with Next, Previous, First, Last and numbered actions with a custom navigation logic.

 

Step 3: Consume the DataTable component

Finally, we will consume the Datatable component in the App component.

import React from "react";
import DataTable from "./DataTable";

function App() {
  return (
    <div className="App">
      <DataTable />
    </div>
  );
}
export default App;

 

 

Conclusion

In this tutorial, we learned how to create a pagination system for a data table using React. We used functional components and the react-bootstrap library to create the pagination component. We also learned how to implement server-side pagination to improve the performance of the application and reduce the load on the client side. With the steps provided, you should be able to create a pagination system for your data tables in React.

Leave a Reply

Your email address will not be published. Required fields are marked *