Table of Contents
Understanding Server-Side Pagination in ReactJS
Working with large datasets can often lead to performance issues in web applications. To ensure a smooth user experience, implementing pagination is crucial. While client-side pagination is easier to implement, server-side pagination is a more efficient solution for large datasets. This blog will guide you through setting up server-side pagination in ReactJS using the React-Paginate library.
What is Pagination and Why is It Important?
Pagination is a UI design pattern that splits data into separate pages, making it easier to navigate and consume. For large datasets, server-side pagination is a necessity as it fetches only a subset of data from the server, reducing memory usage and improving load times.
Key benefits of pagination include:
- Improved Performance: Handles data efficiently, reducing load times.
- Enhanced User Experience: Organizes data into manageable chunks.
- Scalability: Ideal for applications handling dynamic and large datasets.
Why Use React-Paginate for Server-Side Pagination?
React-Paginate is a popular React library that provides a customizable pagination component. It simplifies the task of rendering pagination controls and managing page state.
Features of React-Paginate:
- Customizable UI: Flexible styling options for seamless integration into your app.
- Event Handling: Provides hooks for page change events, making API calls straightforward.
- Accessibility: Built-in support for ARIA attributes ensures compliance with accessibility standards.
Setting Up a Pageable Table in ReactJS
Step 1: Install React-Paginate
Begin by installing React-Paginate using npm or yarn:
npm install react-paginate
Step 2: Backend Setup
Ensure your server API supports pagination by implementing query parameters such as page
and limit
. Here’s an example for a Node.js/Express backend:
app.get('/data', (req, res) => {
const { page = 1, limit = 10 } = req.query;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const paginatedData = data.slice(startIndex, endIndex);
res.json({ total: data.length, data: paginatedData });
});
Building the ReactJS Frontend
Step 3: Fetching Paginated Data
Use the fetch
API or Axios to call the server and retrieve paginated data.
const fetchData = async (currentPage) => {
const response = await fetch(`/data?page=${currentPage}&limit=10`);
const result = await response.json();
setData(result.data);
setTotalPages(Math.ceil(result.total / 10));
};
Step 4: Integrate React-Paginate
Add React-Paginate to your component and handle page change events.
import ReactPaginate from 'react-paginate';
const PageableTable = () => {
const [data, setData] = useState([]);
const [totalPages, setTotalPages] = useState(0);
useEffect(() => { fetchData(1); }, []);
const handlePageClick = (event) => {
fetchData(event.selected + 1);
};
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{data.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
</tr>
))}
</tbody>
</table>
<ReactPaginate
pageCount={totalPages}
onPageChange={handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
</div>
);
};
Customizing React-Paginate
React-Paginate provides several options to customize the pagination controls:
- pageCount: Total number of pages.
- pageRangeDisplayed: Number of page buttons to display.
- marginPagesDisplayed: Number of pages displayed at the beginning and end.
- containerClassName: CSS class for pagination container.
- activeClassName: CSS class for the active page.
Example customization:
<ReactPaginate
previousLabel={'Prev'}
nextLabel={'Next'}
pageCount={totalPages}
onPageChange={handlePageClick}
pageRangeDisplayed={5}
marginPagesDisplayed={2}
containerClassName={'pagination-container'}
activeClassName={'pagination-active'}
/>
Styling Pagination Controls
Use CSS to style the pagination controls:
.pagination-container {
display: flex;
list-style: none;
padding: 0;
}
.pagination-active a {
font-weight: bold;
color: #007bff;
}
Conclusion
Server-side pagination in ReactJS using React-Paginate offers a scalable solution for managing large datasets. By efficiently fetching and displaying data, you can enhance your application’s performance and user experience. With the tips and code provided in this guide, implementing server-side pagination is straightforward and effective.
Leave a Reply