cod;nncode. learn. thrive.

Table Pagination tutorial in Reactjs using Server Side API data with Paginate, CSS example

Posted Sept 17, 2023

Demo

React Pageable Introduction

Imagine you have a super cool toy box, and inside, you've got TONS of toys 🚗. But, it's a bit tricky to find your favorite toys because there are so many of them! 😕

Now, think of your computer screen as your toy box, and we're going to use "React.js" to make it super easy to find and play with your toys on the screen.

We're going to learn some magic tricks like "react pageable" and "react paginate" 🪄, which will help you see your toys one page at a time. No more searching through all of them! We'll even give your toy box a cool new look with some colorful decorations (CSS) 🎨.

But wait, there's more! We'll connect your toy box to a special delivery service (API) 🚚, so you can get new toys whenever you want! And to make sure you really understand all of this, we'll show you lots of fun examples along the way!

So, are you ready to start this amazing adventure? Let's go! 🚀

Table of Contents

  1. Server Side Pagination React

    a. Server Side Pagination setup in Node.js
    b. React Pagination without any library and CSS

  2. React Paginate Tutorial

  3. React Paginate with CSS Tutorial

  4. Conclusion

  5. FAQs

1. Server Side Pagination React

1(a). Server Side Pagination setup in Node.js

Lets set up the our backend first.

Steps -

  1. Create a folder 'server' in your working directory.
  2. Create a file 'index.js' in the 'server' folder
  3. Open terminal and run below command -
npm init -y
  1. Install express by running following command
npm i express
  1. Create a file 'db.json' which will carry our mock data.
Put this sample data their -
[
  {
    "id": 1,
    "name": "Kincaid Wink"
  },
  {
    "id": 2,
    "name": "Charles Jobbings"
  },
  {
    "id": 3,
    "name": "Derrik Dadd"
  },
  {
    "id": 4,
    "name": "Lothario Blucher"
  },
  {
    "id": 5,
    "name": "Aleksandr Doram"
  },
  {
    "id": 6,
    "name": "Octavius Gaw"
  },
  {
    "id": 7,
    "name": "Carolyn Broomfield"
  },
  {
    "id": 8,
    "name": "Aaren Parker"
  },
  {
    "id": 9,
    "name": "Josiah Novotne"
  },
  {
    "id": 10,
    "name": "Dev Stroobant"
  },
  {
    "id": 11,
    "name": "Jordain Nottingam"
  },
  {
    "id": 12,
    "name": "Liana Evetts"
  },
  {
    "id": 13,
    "name": "Vilma Lomasney"
  },
  {
    "id": 14,
    "name": "Marinna Jaqueme"
  },
  {
    "id": 15,
    "name": "Charlean Phethean"
  },
  {
    "id": 16,
    "name": "Ronda Mc Menamin"
  },
  {
    "id": 17,
    "name": "Nicolle Simm"
  },
  {
    "id": 18,
    "name": "Myrlene Gawith"
  },
  {
    "id": 19,
    "name": "Herschel Yesenev"
  },
  {
    "id": 20,
    "name": "Dulcine Buller"
  }
]
  1. Create endpoint in index.js file using this code -
index.js
const db = require("./db.json");
const express = require("express");
const app = express();

app.get("/users", (req, res) => {
  const limit = parseInt(req.query.limit);
  const offset = parseInt(req.query.offset);

  const users = db.slice(offset, offset + limit);
  const totalCount = db.length;

  res.header("Access-Control-Allow-Origin", "*");
  res.json({ users, totalCount });
});

app.listen(8000, () => {
  console.log("Server started...");
});

Here, we created an API endpoint on our server '/users' which returns list of users.

Example call - "http://localhost:8000/users?limit=5&offset=0"

It takes two query params -

  • limit = 5
  • offset = 0

'limit' means how many items/users we want from our array 'offset' means at which index we need to start picking.

So, in this case, from index '0' (offset) pick '5' (limit) users.

Response -

{
  "users": [
    { "id": 1, "name": "Kincaid Wink" },
    { "id": 2, "name": "Charles Jobbings" },
    { "id": 3, "name": "Derrik Dadd" },
    { "id": 4, "name": "Lothario Blucher" },
    { "id": 5, "name": "Aleksandr Doram" }
  ],
  "totalCount": 20
}

Note: We have 'res.header("Access-Control-Allow-Origin", "*");' code, this will make our API request successful when we call it from React, read more about CORS error.

SERVER DONE!

1(b). React Pagination without any library and CSS

Let's setup our Client.

Steps -

  1. Create a file Pagination.jsx in your React project.

  2. Put this code in it -

Pagination.jsx
import React, { useEffect, useState } from "react";

const LIMIT = 5;

const Pagination = () => {
  const [offset, setOffset] = useState(0);
  const [totalCount, setTotalCount] = useState(0);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchUsers(offset);
  }, [offset]);

  const fetchUsers = async (page) => {
    try {
      const response = await fetch(
        `http://localhost:8000/users?limit=${LIMIT}&offset=${offset}`
      );
      const { users, totalCount } = await response.json();
      setUsers(users);
      setTotalCount(totalCount);
    } catch (error) {
      console.log(error);
    }
  };

  const handlePrevPage = () => {
    if (offset <= 0) {
      return;
    }

    setOffset(offset - LIMIT);
  };

  const handleNextPage = () => {
    if (offset + LIMIT >= totalCount) {
      return;
    }

    setOffset(offset + LIMIT);
  };

  return (
    <div>
      {/* Display the users */}
      {users.map((user) => (
        <div key={user.id}>
          #{user.id} | {user.name}
        </div>
      ))}

      {/* Pagination controls */}
      <button onClick={handlePrevPage}>Previous Page</button>
      <button onClick={handleNextPage}>Next Page</button>
    </div>
  );
};

export default Pagination;

Explanation -

  1. Three states - offset - We will change this offset value on click of "Previous Page" and "Next Page" buttons totalCount - This will restrict user to hit Next or Previous if data is not there. users - This will carry list of users

  2. useEffect - On change of 'offset' state we will call fetchUsers method.

  3. fetchUsers - Hitting our API created earlier in Node.js

  4. The handlePrevPage and handleNextPage functions update the offset state, allowing the user to navigate to the previous and next pages. We disable the pagination controls when the user is on the first or last page to prevent invalid navigation.

2. React Paginate Tutorial

Here the code is mostly similar to 1(b). Only thing is changed is the use ReactPaginate in JSX and the onClick 'handlePageClick' method.

Steps -

  1. Install 'react-paginate' package using this command.
npm i react-paginate
  1. Create a file PaginationWithLibrary.jsx in your React project.

  2. Put this code in it -

PaginationWithLibrary.jsx
import ReactPaginate from "react-paginate";
import { useEffect, useState } from "react";
import "./PaginationWithLibrary.css";
const LIMIT = 5;

export default function PaginationWithLibrary() {
  const [offset, setOffset] = useState(0);
  const [totalCount, setTotalCount] = useState(0);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchUsers(offset);
  }, [offset]);

  const fetchUsers = async (page) => {
    try {
      const response = await fetch(
        `http://localhost:8000/users?limit=${LIMIT}&offset=${offset}`
      );
      const { users, totalCount } = await response.json();
      setUsers(users);
      setTotalCount(totalCount);
    } catch (error) {
      console.log(error);
    }
  };

  const handlePageClick = (event) => {
    const newOffset = event.selected * LIMIT;
    if (newOffset < 0 || newOffset >= totalCount) {
      return;
    }

    setOffset(newOffset);
  };

  return (
    <div className="App">
      <div className="list">
        {users.map((user) => (
          <div key={user.id} className="list-item">
            {user.id}. {user.name}
          </div>
        ))}
      </div>
      <ReactPaginate
        onPageChange={handlePageClick}
        pageCount={totalCount / users.length}
        previousLabel={<button>Previous Page</button>}
        nextLabel={<button>Next Page</button>}
      />
    </div>
  );
}

Explanation -

  1. State and useEffect logic same as 1(b)
  2. Imported and used ReactPaginate component given by 'react-paginate' library.
  3. handlePageClick method will be called when we change our page. We disable the pagination controls when the user is on the first or last page to prevent invalid navigation by returning the method.

3. React Paginate with CSS Tutorial

Steps -

  1. First update the "PaginationWithLibrary.jsx" JSX code to support CSS in "ReactPaginate" component.
<ReactPaginate
  containerClassName="pagination"
  activeClassName="active"
  pageClassName="page-item"
  onPageChange={handlePageClick}
  breakLabel="..."
  pageCount={totalCount / users.length}
  previousLabel={<button>Previous Page</button>}
  nextLabel={<button>Next Page</button>}
/>

For the previous (2) section, you can put this CSS in "PaginationWithLibrary.css" file.

PaginationWithLibrary.css
.App {
  display: flex;
  font-family: sans-serif;
  margin: 0 auto;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 90vh;
}

.pagination {
  list-style: none;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  cursor: pointer;
  font-family: monospace;
  padding: 0;
}

.active {
  background-color: #1ec6ff;
  border-radius: 10px;
}

.page-item {
  list-style: none;
  padding: 2px 5px;
  height: 30px;
  width: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px;
}

.previous button,
.next button {
  background-color: none;
  border-radius: 10px;
  height: 40px;
  padding: 5px 10px;
  border: 1px solid #d4d4d4;
}

.previous button:hover,
.next button:hover {
  cursor: pointer;
  background-color: #1ec6ff;
}

.list {
  width: 400px;
  border: 1px solid #d4d4d4;
  border-radius: 10px;
  padding: 10px;
  display: grid;
  row-gap: 10px;
}

.list-item {
  height: 30px;
  display: flex;
  align-items: center;
  padding: 5px;
}

.list-item:nth-child(2n) {
  background-color: #eeeeee;
}

4. Conclusion

We've reached the end of our exciting journey into React.js pageable and paginate magic. With CSS, APIs, and server-side pagination in Node.js, you're now a web wizard! 🧙‍♂️

Keep exploring and coding, and remember that the web world is full of adventures waiting for you. Happy coding! 🚀👩‍💻

5. FAQs

Q1: What is React pagination, and why is it important in web development?

React pagination is a technique that breaks down a large set of data into smaller, more manageable chunks or pages. It's important in web development because it improves user experience by making it easier to navigate and access content, particularly in situations where there's a large amount of data to display.

Q2: How do I implement basic pagination in a React application without using external libraries or packages?

To implement basic pagination in React without external libraries, you can manage the page number and number of items per page in your component's state. Then, use this state to slice and display the data accordingly. Implement "Previous" and "Next" buttons to update the page number.

Q3: What are the advantages of using pagination libraries like "react-paginate" in a React project?

Pagination libraries like "react-paginate" provide pre-designed, customizable pagination components that save development time. They often include features like page number rendering, handling click events, and styling options, making it easier to create a polished pagination system.

Q4: How can I handle sorting and filtering in combination with pagination in a React application?

To handle sorting and filtering in combination with pagination, you can maintain state for sorting and filtering criteria. Apply these criteria to your data before performing pagination. When users change sorting or filtering options, update the state and reapply the criteria to update the displayed data.

Q5: What's the difference between client-side and server-side pagination, and when should I use each one?

Client-side pagination involves managing and paginating data entirely on the client side, while server-side pagination retrieves and paginates data from the server. Use client-side pagination for small datasets as it simplifies implementation. For large datasets or when performance is critical, opt for server-side pagination to reduce data transfer and improve loading times.

Further Resources

React 19: New Features List [Interview Ready]

Get interview-ready with our comprehensive guide on React 19, covering its groundbreaking advancements, new features, improved performance, and backward compatibility.

Read Here

Git How to Stash

The `git stash` command is used to stash changes in the working directory. This command saves changes in the stash stack, which can later be applied or popped.

Read Here

CRUD Operations in ReactJS Without API: GitHub Code Step-by-Step Example 2024

This article dives into implementing CRUD operations specifically in ReactJS without relying on an external API, providing a comprehensive step-by-step guide and a GitHub code example.

Read Here

JavaScript Object Creation: Mastering Classes and Prototypes for Efficiency

Explore different methods of creating objects in JavaScript, with a focus on the 'class' keyword. Learn when to use each approach and the benefits they offer.

Read Here

Learn how to create two simple responsive side navigation bar and main navbar in ReactJs

Learn how to create a simple two responsive side navigation bar and navbar in React JS to enhance user experience and create a more interactive web application.

Read Here
Your feedback is our favorite notification! Share your thoughts about this page and make us smile.