DEV Community

Cover image for Build React Pagination using React Paginate
Jack Pritom Soren
Jack Pritom Soren

Posted on

4 2

Build React Pagination using React Paginate

We often work with web applications that need to fetch large amounts of data from a server through APIs and render it on the screen.

For example, in a Social media application we fetch and render users' posts and comments. In an HR dashboard we display information about candidates who applied for a job. And in an Email Client we show the a user's emails.

Rendering all the data at once on the screen can cause your webpage to slow down considerably because of the large number of DOM elements present in the webpage. If we want to optimize on performance we can adopt various techniques to render data in a more efficient manner. Some of these methods include infinite scroll with virtualization and pagination.

Tools and Packages:
React
JSON Placeholder
react-paginate
Bootstrap

App.js

import "./App.css";
import ReactPaginate from "react-paginate";
import { useEffect, useState } from "react";

const App = () => {
  const [items, setItem] = useState([]);
  const [pageCount, setpageCount] = useState(0);
  let limit = 12;

  useEffect(() => {
    const getComments = async () => {
      const res = await fetch(
        `https://jsonplaceholder.typicode.com/comments?_page=1&_limit=${limit}`
      );
      const data = await res.json();
      const total = res.headers.get("x-total-count");
      setpageCount(Math.ceil(total / 12));
      setItem(data);
    };
    getComments();
  }, []);

  const fetchComments = async (currentPage) => {
    const res = await fetch(
      `https://jsonplaceholder.typicode.com/comments?_page=${currentPage}&_limit=12`
    );
    const data = await res.json();
    return data;
  };

  const handleClick = async (data) => {
    let currentPage = data.selected + 1;
    const commentsFormServer = await fetchComments(currentPage);
    setItem(commentsFormServer);
  };

  return (
    <div>
      <div className="row m-2">
        {items.map((item) => {
          return (
            <div key={item.id} className="col-sm-6 col-md-4 v my-2">
              <div className="card shadow-sm w-100" style={{ minHeight: 225 }}>
                <div className="card-body">
                  <h5 className="card-title text-center h2">Id :{item.id} </h5>
                  <h6 className="card-subtitle mb-2 text-muted text-center">
                    {item.email}
                  </h6>
                  <p className="card-text">{item.body}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <ReactPaginate
        previousLabel={"previous"}
        nextLabel={"next"}
        breakLabel={"..."}
        pageCount={pageCount}
        marginPagesDisplayed={2}
        pageRangeDisplayed={2}
        onPageChange={handleClick}
        containerClassName={"pagination justify-content-center"}
        pageClassName={"page-item"}
        pageLinkClassName={"page-link"}
        previousClassName={"page-item"}
        previousLinkClassName={"page-link"}
        nextClassName={"page-item"}
        nextLinkClassName={"page-link"}
        breakClassName={"page-item"}
        breakLinkClassName={"page-link"}
        activeClassName={"active"}
      />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Github Repository Link: Github

Follow me on : Github Linkedin

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay