How to implement pagination in React using Hooks?
Implementing pagination in React using Hooks:
- Setup Initial State: Use the
useState
hook to manage the state for the current page and items per page.
import React,
{
useState
} from 'react';
function App() {
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(20);
// write code
}
- Render Data Based on Pagination: Use the state variables to calculate which portion of the data to display.
- Handle Pagination Actions: Implement functions to handle navigation between pages.
- Render Pagination Controls: Render buttons or links to allow users to navigate through pages.
Example: Below is an example of pagination in React using Hooks.
Javascript
import React, { useState } from 'react' function App() { const [currentPage, setCurrentPage] = useState(1); const [itemsPerPage, setItemsPerPage] = useState(10); const data = [ { id: 1, name: 'GeekforBeginner 1' }, { id: 2, name: 'GeekforBeginner 2' }, { id: 3, name: 'GeekforBeginner 3' }, { id: 4, name: 'GeekforBeginner 4' }, { id: 5, name: 'GeekforBeginner 5' }, { id: 6, name: 'GeekforBeginner 6' }, { id: 7, name: 'GeekforBeginner 7' }, { id: 8, name: 'GeekforBeginner 8' }, { id: 9, name: 'GeekforBeginner 9' }, { id: 10, name: 'GeekforBeginner 10' }, { id: 11, name: 'GeekforBeginner 11' }, { id: 12, name: 'GeekforBeginner 12' }, { id: 13, name: 'GeekforBeginner 13' }, { id: 14, name: 'GeekforBeginner 14' }, { id: 15, name: 'GeekforBeginner 15' }, { id: 16, name: 'GeekforBeginner 16' }, { id: 17, name: 'GeekforBeginner 17' }, { id: 18, name: 'GeekforBeginner 18' }, { id: 19, name: 'GeekforBeginner 19' }, { id: 20, name: 'GeekforBeginner 20' }, ]; function renderData() { const startIndex = (currentPage - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; const currentItems = data.slice(startIndex, endIndex); return ( <ul> { currentItems.map(item => ( <li key={item.id}>{item.name}</li> )) } </ul> ); } function goToNextPage() { setCurrentPage(prevPage => prevPage + 1); } function goToPrevPage() { setCurrentPage(prevPage => prevPage - 1); } function goToSpecificPage(pageNumber) { setCurrentPage(pageNumber); } function renderPaginationControls() { const totalPages = Math.ceil(data.length / itemsPerPage); return ( <div> <button onClick={goToPrevPage} disabled={currentPage === 1}> Previous </button> { Array.from({ length: totalPages }, (_, i) => ( <button key={i} onClick={ () => goToSpecificPage(i + 1) }> {i + 1} </button> )) } <button onClick={goToNextPage} disabled={currentPage === totalPages}> Next </button> </div> ); } return ( <div> {renderData()} {renderPaginationControls()} </div> ); } export default App; |
Output:
Contact Us