Back

Pagination in React Js

Copy Below Code View As A Text File Show Text Only Show API Edit Code
                            

==== Pagination ==== I manually create the Pagination code so that it can work in Class component and in React Function as well. I created two files Blogs.js (Where pagination needs to be implimented) and a Global Pagination File. i.e. pagination.js ==== Blogs.js === const [posts,setPosts] = useState([]); const [currentPage,setCurrentPage]=useState(1); const [postsPerPage,setPostsPerPage]=useState(2); useEffect(() => {} or componentDidMount() const indexOfLastPost=currentPage * postsPerPage; const indexOfFirstPost=indexOfLastPost - postsPerPage; const currentPosts = posts.slice(indexOfFirstPost,indexOfLastPost); // Change Page const paginate = (pageNumber) => setCurrentPage(pageNumber); // This Method will change the Page {/* Pagination Component */} <Pagination postsPerPage={postsPerPage} totalPosts={staff.length} paginate={paginate} currentPage={currentPage}/> === Pagination.js === import React from 'react'; const Pagination = ({postsPerPage , totalPosts,paginate,currentPage}) => { const pageNumbers =[]; for(let i=1; i<= Math.ceil(totalPosts / postsPerPage); i++){ pageNumbers.push(i); } return ( <nav> <ul className="pagination"> {pageNumbers.map(number => ( <li key={number} className={"page-item "+ (number === currentPage ? 'active' : '')} > {console.log(number,currentPage)} <a onClick={() => paginate(number)} className="page-link "> {/* Onclick Method present in main file. */} {number} </a> </li> ))} </ul> </nav> ); }; export default Pagination;