Categories
Examples MERN Stack Next js React-js

Built your own React Pagination System

Do you ever wonder why do we need to build a custom react pagination System? Or while setting up the project why we do we need a to setup a react pagination component as well? Or How do I use custom pagination system in react JS? We are going to answer these questions in this article.

It is not possible to render large items in a single list. Even if you are building simple application like the Todo List app it is inevitable that you must add some kind of pagination system. Either you can choose some fancy components from popular UI libraries like React Bootstrap Pagination, Ant design or Material UI, or you choose some third-party package to deliver the pagination system like React-Pagination. But it is very important to have a pagination system in your React application.

Today we are going to talk about how to implement a very basic react pagination system from scratch. It would be a very good exercise to brush up your JavaScript and React skills. This react pagination component would also give beginners enough hand on experience to play with React Basics. So, without wasting any time let’s get started.

Simple Pagination CSS

First of all, let’s take care of the CSS which we need in our react pagination component. So that, we don’t have to worry about react pagination CSS later. This react pagination CSS could be as simple as making the page index buttons a little square and giving a different color to the active page button from rest of the buttons. So here is the complete CSS for the React Pagination Component.

.pagination-controls {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination-controls button {
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination-controls button.active {
  background-color: #007bff;
  color: #fff;
  border-color: #007bff;
}
Code language: CSS (css)

The Problem

Next thing we need to add few states to take care of the react pagination. Let’s assume that we want to paginate the `<ul></ul>` list which is rendering the Todo Items in our React Component. If we need to convert that full lengthy todo list into react pagination list, we need to declare few states.

const [todoList, setTodoList] = useState([]);Code language: JavaScript (javascript)

Previously Rendered TodoList

Before we jump into building the pagination we need to look into how we are rendering our existing list. In the following code you may see that we are simply rendering it with javaScript built in map function. So, we are actually using todoList.map((item, index) => ( to render our list and here the todoList is the existing list which we want to paginate.

 <ul className='todo-list'>
          {todoList.map((item, index) => (
            <li key={index}
              className='list-item'
            >
              <span>{item.todoText}</span>
              <span className="icons">

                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="feather feather-trash"
                  title="Delete"
                  onClick={() => handleDelete(index)}
                >
                  <polyline points="3 6 5 6 21 6"></polyline>
                  <path d="M16 6v-1a4 4 0 0 0-4-4h-4a4 4 0 0 0-4 4v1"></path>
                  <line x1="8" y1="11" x2="10" y2="11"></line>
                  <line x1="10" y1="11" x2="10" y2="17"></line>
                  <line x1="14" y1="11" x2="14" y2="17"></line>
                </svg>
              </span>
            </li>
          ))}
        </ul>
Code language: HTML, XML (xml)

External Links to other examples

Here are few ways to implement the pagination from scratch in react.js on stackoverlfow. You may need to check out this as well. In one of another stackoverflow page there is also antd based pagination examples available.

Adding Pagination State

Now we need to add pagination states into this component. First of all, we need to use a state where we can hold the current page number and also the paginated list rather than the complete list. So that we would be able to render the paginated list only. Which means to render only those items which are in range of that page number. So, by default, the page number would be 1 in the react pagination component and the constant number is required to hold how many items per page do we need. Although we can create a combo box or drop-down menu to ask user to define the number of items per page but for the sake of simplicity, we will make it constant to not add over complexity to a very simple problem we are going to tackle here. Here are the state and constant for our pagination component.

const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5; // Set the number of items per page

Code language: JavaScript (javascript)

Slice Data for Pagination

Next thing, we need to do is to do some calculations based on this current page number and items per page information in our react pagination component. As you may already assume, we need to find out total number of items in the `todoList` array before we jump into the calculation of react pagination controls. Also, based on this information we need to splice the `todoList` array to later use in the react pagination rendering. Here is how we can achieve this.

const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = todoList.slice(indexOfFirstItem, indexOfLastItem);
Code language: JavaScript (javascript)

As you see, we first calculated the index of Frist Last and First Item and based on this we simple call the slice function of JavaScript to slice the complete todoList into a shorter chunk which we will render instead of complete `todoList` in our main component.

{currentItems.map((item, index) => (
  <li key={index} className='list-item'>
    {/* ... Rest of your item rendering code ... */}
  </li>
))}
Code language: JavaScript (javascript)

Create Pagination Controls

Next thing we need to build a custom pagination component which will help in pagination in react js. By creating this controls we can use to navigate through all over the pages. The same kind of react pagination component could be used for table data navigation just like we are using the React pagination by building a custom pagination component. We will make it as simple as possible to just demonstrate the logic and bare minimum implementation. So, we create a new component which we can embed into the same component responsible for all of rendering or we can also create a separate new component. Whichever suits you the most but I am going to put it into the same code base.

const totalPages = Math.ceil(todoList.length / itemsPerPage);

const handlePageChange = (newPage) => {
  setCurrentPage(newPage);
};

const paginationControls = Array.from({ length: totalPages }, (_, index) => (
  <button
    key={index}
    onClick={() => handlePageChange(index + 1)}
    className={currentPage === index + 1 ? 'active' : ''}
  >
    {index + 1}
  </button>
));
Code language: JavaScript (javascript)

Here you can see, we first created the calculation of total number of pages to render the complete List. Which is pretty straight forward to calculate by dividing the total length of the list with the required items per page. Based on this information we just created an Array of buttons and applied the `active` class on to the currentPage variable. Because the first index of the array always starts from 0, that’s why we need to add +1 into the displaying index.

Finally, we can display this Pagination Control Buttons array with like this.

<ul className='todo-list'>
  {currentItems.map((item, index) => (
    // ... Rest of your item mapping code ...
  ))}
</ul>
<div className='pagination-controls'>{paginationControls}</div>Code language: HTML, XML (xml)

Final Note

Finlay, we implemented a basic react pagination system in React.js hope so far this would be the best learning journey for you and let’s keep in mind you may need to enhance this according to your requirements and always take this code as learning exercise. Also keep in mind in some real application you may need to use the third-party library and should not focus on writing the complete code by yourself. As this is very limited implementation. Which render limited items per page and provide the pagination control buttons to navigate between pages.

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.