Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created August 1, 2020 18:32
Show Gist options
  • Select an option

  • Save 0ex-d/ea40f0c4bad10b108a4fbdb0d8d71bbe to your computer and use it in GitHub Desktop.

Select an option

Save 0ex-d/ea40f0c4bad10b108a4fbdb0d8d71bbe to your computer and use it in GitHub Desktop.
Pagination component using ReactJs for your bulky data pages or dashboard.
// 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)}>&lt;&lt;</div></li>
<li><div className="link is-active" onClick={() => setPage(page)}>{page}/{totalPages}</div></li>
<li><div className="link" onClick={() => handlePageChange(1)}>&gt;&gt;</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