Pagination Component using React Hooks
Last Updated :
01 Apr, 2024
Pagination on websites refers to the way of displaying a large set of data in smaller chunks. In React, it's super easy to create a pagination component with the help of the `useEffect` and `useState` hooks. we will create a pagination component using React hooks.
Output Preview: Let us have a look at how the final output will look like.

Prerequisites
Approach to create Pagination Component
The approach is very simple. We will count the array length and divide it with the number of elements that we wants to display per page. The resultant will be the total number of pages that will be rendered on a single page. We will utilize useState to store these results for conditional rendering.
Steps to Create React App & Install required modules
Step 1: Create a new react app and enter into the folder created by running the following command.
npx create-react-app react-pagination
cd react-pagination
Step 2: Install tailwindcss and initialize it by running the following command.
npm install tailwindcss
npx tailwindcss init
Step 3: Create a Paginatination Component to write the pagination logic.
Folder Structure:
project structureDependencies List: Open package.json and verify the following dependencies.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"tailwindcss": "^3.4.1",
"web-vitals": "^2.1.4"
}
Example Code: Here are the codes for working example of a pagination component with react hooks.
CSS
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
transition: 0.5s ease-in-out;
}
JavaScript
// src/PaginationComponent.js
import React, { useState, useEffect } from 'react';
function PaginationComponent() {
const [todos, setTodos] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage] = useState(12);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos`);
const data = await response.json();
setTodos(data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
const randomLightColor = () => {
const randomColor = () => Math.floor(Math.
random() * 200) + 56;
return `rgb(${randomColor()},
${randomColor()}, ${randomColor()})`;
};
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = todos.
slice(indexOfFirstItem, indexOfLastItem);
const paginate = (pageNumber) =>
setCurrentPage(pageNumber);
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length /
itemsPerPage); i++) {
pageNumbers.push(i);
}
return (
<div className="max-w-3xl mx-auto p-4">
<h1 className="text-2xl text-green-800
font-bold mb-6">Pagination @GeeksforGeeks</h1>
<div className="grid grid-cols-4 gap-4">
{currentItems.map((todo) => (
<div key={todo.id}
className={`h-40 text-gray-800 p-4
rounded-sm shadow-xl`}
style={{ backgroundColor: randomLightColor()}}>
<h2 className="text-sm font-semibold mb-2">
{todo.title}
</h2>
<p className="text-gray-700
text-md">{todo.completed ?
'Completed': 'Not Completed'}</p>
</div>
))}
</div>
<ul className="flex gap-2 justify-center
flex-wrap mt-8">
{pageNumbers.map((number) => (
<li key={number} className="">
<button
onClick={() => paginate(number)}
className={`px-3 py-1 rounded-full
${currentPage === number
? 'bg-green-700 text-white'
: 'bg-gray-200 text-gray-700'
}`}
>
{number}
</button>
</li>
))}
</ul>
</div>
);
}
export default PaginationComponent;
JavaScript
// src/App.js
import './App.css';
import PaginationComponent from './PaginationComponent';
function App() {
return (
<div className="App">
<PaginationComponent/>
</div>
);
}
export default App;
JavaScript
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [],
}
To Run the Application: Open terminal at the root of project and run the following command to start the server.
npm start
Output:

Similar Reads
ReactJS Reactstrap Pagination Component
Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Pagination component allows the users to easily switch between pages across a website or app. We can use the following approach in Rea
4 min read
Create a Modal Component using React Hooks
In this article, we are going to build a modal component using React Hooks. The modal is going to be a user register form modal that will appear on a button click. The modal will utilize the useState hook for its state management. Output Preview: Let us have a look at how the final output will look
4 min read
How to implement pagination in React using Hooks?
Implementing pagination in React using hooks involves managing the state of the current page and the number of items per page, as well as rendering the paginated data accordingly. Implementing pagination in React using Hooks:Setup Initial State: Use the useState hook to manage the state for the curr
3 min read
How to Map Data into Components using ReactJS?
Mapping data in react js component is a comman practice to render the lists and repeating elements. In this article, we will have a users data and we will map it to react components to display the users information in the react appPrerequisites:React JSNodejs and npmJavaScript Array mapApproachTo ma
3 min read
React-Bootstrap Pagination Component
React-Bootstrap is a front-end framework that was designed keeping react in mind. Pagination Component provides a way for users to switch between pages easily. It is basically a set of presentational components for providing a better UI experience to the user. We can use the following approach in Re
2 min read
ReactJS Functional Components
In ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Native Smart Components
In this article, we are going to learn about Smart components in React Native. The smart component is one of the categories of React Components so before diving into the smart components detail. A Component is one of the core building blocks of React and React-Native. The component is a block of cod
3 min read
How to Test React Components using Jest ?
React is a frontend open-source JavaScript library, used to build interactive User Interfaces. React is focused on Single Page applications and is more popularly known as a SPA. Testing is an important aspect of development. It examines whether the application is behaving as intended, and protects i
6 min read
Context Hooks in React
Context Hooks are a feature in React that allows components to consume context values using hooks. Before Hooks, consuming context required wrapping components in Consumer or using a Higher Order Component (HOC). Context Hooks streamline this process by providing a more intuitive and concise way to
3 min read
How to use componentWillMount() in React Hooks?
The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like Com
2 min read