Implement Pagination in your React js Application
React is a popular JavaScript library for building user interfaces. When building a web application with React, it is common to display a large amount of data in a table or a list. In such cases, it is important to implement pagination to make the data more manageable and improve the user experience.
Here, we will discuss how to implement pagination in a React.js application. We will use the example of displaying a list of items and adding pagination to it.
Setting up the Environment
First, make sure you have Node.js and npm installed on your computer. To create a new React application, you can use the ‘create-react-app’ package using npm.
“`bash
npx create-react-app pagination-demo
cd pagination-demo
npm start
“`
Creating the Component
Now, let’s create a new component called ‘ItemList’ that will display the list of items and implement pagination. We will use the useState hook to manage the state of the component.
“`javascript
import React, { useState } from ‘react’;
const ItemList = () => {
const items = […]; // array of items to display
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem – itemsPerPage;
const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);
const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};
return (
))}
);
};
export default ItemList;
“`
Implementing Pagination Component
Next, we will create a new component called ‘Pagination’ that will render the pagination UI and handle page changes.
“`javascript
import React from ‘react’;
const Pagination = ({ itemsPerPage, totalItems, currentPage, onPageChange }) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(totalItems / itemsPerPage); i++) {
pageNumbers.push(i);
}
return (
);
};
export default Pagination;
“`
Using the ItemList Component
Now, you can use the ItemList component in your main App component and display the paginated list of items.
“`javascript
import React from ‘react’;
import ItemList from ‘./ItemList’;
const App = () => {
return (
Paginated List of Items
);
};
export default App;
“`
Conclusion
Implementing pagination in a React.js application is essential for managing large sets of data. By creating a reusable Pagination component and using the useState hook, you can easily add pagination functionality to your application. This will improve the user experience and make your application more user-friendly.