Created
August 1, 2020 18:32
-
-
Save 0ex-d/ea40f0c4bad10b108a4fbdb0d8d71bbe to your computer and use it in GitHub Desktop.
Pagination component using ReactJs for your bulky data pages or dashboard.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Handling pagination with React hooks | |
| // React | |
| // By Precious Akin | |
| import React, { | |
| useEffect, useState | |
| } from 'react'; | |
| const Page = () => { | |
| const [page, setPage] = useState(1); // first page | |
| const [totalPages, setTotalPages] = useState(0); | |
| const limit = 12; | |
| // on DOM load, set total pages | |
| // the '_data' variable can be some dummy object or sourced from JSON | |
| useEffect(()=>{ | |
| let _data = {}; | |
| setTotalPages(Math.round(_data.length / limit)); | |
| },[]); | |
| // this updates our current visible page index | |
| // say; currIndex =2 then (currIndex + (-1)) would take us | |
| // to the previous page | |
| const handlePageChange = (direction) => { | |
| if (page + direction > totalPages || page + direction <= 0) { | |
| return false; | |
| } else { | |
| setPage(page + direction); | |
| } | |
| } | |
| return ( | |
| <div> | |
| <ul className="pagination"> | |
| <li><div className="link" onClick={() => handlePageChange(-1)}><<</div></li> | |
| <li><div className="link is-active" onClick={() => setPage(page)}>{page}/{totalPages}</div></li> | |
| <li><div className="link" onClick={() => handlePageChange(1)}>>></div></li> | |
| </ul> | |
| </div> | |
| ) | |
| } | |
| export default Page; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment