React: how to paginate data

React: how to paginate data

In this article, we will explore how to implement pagination of the results of an API request in a React application.

When developing a web application in React that requests data from a server, you are often faced with the problem of how to handle a large amount of data efficiently. One of the common solutions to this problem is pagination. Pagination lets you break up request results into more manageable pages, allowing users to navigate between them. In this article, we will explore how to implement pagination of the results of an API request in a React application.

Create a component for the page

First, it is important to create a React component dedicated to displaying paginated results. This component will include navigation buttons between different pages and will only show data relating to the current page. Here is an example of how a page component might be structured:


import React from 'react';

const ResultsPage = ({ data, currentPage, perPage }) => {
   // Calculate the start and end index for the current page
   const startIndex = (currentPage - 1) * perPage;
   const endIndex = startIndex + perPage;

   // Extract data for the current page
   const pageData = data.slice(startIndex, endIndex);

   return (
     <div>
       {pageData.map((datum) => (
         <div key={datum.id}>{datum.name}</div>
       )}
     </div>
   );
};

export default ResultsPage;

This component receives the complete data, the current page number, and the number of items to display per page. It then calculates the start and end indices to extract only the data relating to the current page and displays it.

Manage page state

To allow users to navigate between different pages, it is necessary to manage the state of the current page. You can do this using React state. Here's an example of how you might do this:


import React, { useState } from 'react';
import ResultsPage from './ResultsPage';

const App = () => {
   const [currentPage, setCurrentPage] = useState(1);
   const perPage = 10; // Specify the number of items to display per page

   // Your complete data should be obtained from a request to the server
   const data = [
     /* ... Your data ... */
   ];

   return (
     <div>
       <ResultsPage data={data} currentPage={currentPage} perPage={perPage} />
       <div>
         <button onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1}>Previous</button>
         <button onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage * perPage >= data.length}>Next</button>
       </div>
     </div>
   );
};

export default App;

In this example, we use the currentPage state and the setCurrentPage() function to manage the current page. The "Previous" and "Next" buttons allow users to navigate between different pages. It is important to handle the case where the user tries to go to a previous page when they are already on the first page or to go to a next page when they are already on the last page.

Optimization and asynchronous data loading

In a real-world application, data is often loaded asynchronously from a server. In this case, it is important to manage data loading and display efficiently. You can use libraries like Axios or the fetch method to make asynchronous HTTP requests to the server and then update the results page component once the data has been received.


import React, { useState, useEffect } from 'react';
import ResultsPage from './ResultsPage';
import axios from 'axios'; // Import Axios or another library of your choice

const App = () => {
   const [currentPage, setCurrentPage] = useState(1);
   const perPage = 10; // Specify the number of items to display per page
   const [data, setData] = useState([]);

   useEffect(() => {
     // Make a request to the server to get the complete data
     axios.get('/api/data')
       .then((response) => {
         setData(response.data);
       })
       .catch((error) => {
         console.error('Error retrieving data:', error);
       });
   }, []); // The empty array ensures that this request is only made once

   return (
     <div>
       <ResultsPage data={data} currentPage={currentPage} perPage={perPage} />
       <div>
         <button onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1}>Previous</button>
         <button onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage * perPage >= data.length}>Next</button>
       </div>
     </div>
   );
};

export default App;

In this example, we use useEffect to make an asynchronous request to the server to get the complete data. Once the data is received, it is set to the state, and the results page component is automatically updated to show the current data.

Conclusions

Paging the results of an API request is an effective way to handle large amounts of data in a React application. By creating a dedicated component for displaying paginated data and managing page state, you can provide users with a smoother browsing experience. Additionally, optimizing asynchronous data loading is critical to ensuring your application runs efficiently. We hope this article has given you a solid foundation for implementing request result pagination in React in your next web application.