A Beginner’s Guide to Creating Pagination in React.js
Creating pagination in React.js is a common requirement when dealing with large sets of data. Pagination allows users to navigate through data in smaller, more manageable chunks. Here’s a beginner’s guide on how to implement pagination in React.js:
Step 1: Set up your React.js project
Before you start implementing pagination, make sure you have a React.js project set up. You can use Create React App or any other preferred method to create your project.
Step 2: Install dependencies
We’ll be using some additional packages for the pagination functionality. Install them by running the following commands in your project’s root directory:
npm install axios # For making HTTP requests (optional - you can use any method to fetch data)
npm install react-bootstrap # For styling pagination (optional - you can use any styling framework)
Step 3: Fetch the data
For demonstration purposes, we’ll assume you want to fetch data from an API. If you already have your data in a local array or any other source, you can skip this step. Here, we’ll use axios
to fetch data from an API:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const YourComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch data from your API or any other source
axios.get('https://your-api-url.com/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
// Rest of your component code
};
Step 4: Implement the Pagination Component
Now, let’s create a reusable Pagination component that you can use in your main component.
import React from 'react';
import { Pagination } from 'react-bootstrap';
const PaginationComponent = ({ currentPage, totalPages, onPageChange }) => {
const handlePageChange = (page) => {
if (page !== currentPage) {
onPageChange(page);
}
};
return (
<Pagination>
<Pagination.First onClick={() => handlePageChange(1)} />
<Pagination.Prev onClick={() => handlePageChange(currentPage - 1)} />
{[...Array(totalPages)].map((_, index) => (
<Pagination.Item
key={index + 1}
active={index + 1 === currentPage}
onClick={() => handlePageChange(index + 1)}
>
{index + 1}
</Pagination.Item>
))}
<Pagination.Next onClick={() => handlePageChange(currentPage + 1)} />
<Pagination.Last onClick={() => handlePageChange(totalPages)} />
</Pagination>
);
};
export default PaginationComponent;
Step 5: Integrate Pagination in your main component
Now, you can integrate the Pagination component into your main component. Remember to manage the current page and the number of items displayed per page:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import PaginationComponent from './PaginationComponent';
const YourComponent = () => {
const [data, setData] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10; // You can change this according to your requirements
useEffect(() => {
// Fetch data from your API or any other source
axios.get('https://your-api-url.com/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
const totalItems = data.length;
const totalPages = Math.ceil(totalItems / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);
const handlePageChange = (page) => {
setCurrentPage(page);
};
return (
<div>
{/* Render your data using the currentItems */}
<ul>
{currentItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
{/* Render the pagination component */}
<PaginationComponent
currentPage={currentPage}
totalPages={totalPages}
onPageChange={handlePageChange}
/>
</div>
);
};
export default YourComponent;
That’s it! You’ve now implemented a basic pagination feature in React.js. As the user clicks on different pages in the pagination component, the displayed data will update accordingly. Remember that this is a simple example, and you can customize the Pagination component and data fetching logic to suit your specific needs.
Join us on Medium to stay updated with our thought-provoking articles, engaging stories, and insightful discussions. Follow our Medium account for a regular dose of inspiration, knowledge, and entertainment. Let’s embark on a journey of learning and exploration together. See you there! 🚀📚