Javascript React Pagination
const [currentPage, setCurrentPage] = useState(1);
const PRODUCTSPERPAGE = 3;
const indexOfLastProduct = currentPage * PRODUCTSPERPAGE;
const indexOfFirstProduct = indexOfLastProduct - PRODUCTSPERPAGE;
const currentList = products.slice(indexOfFirstProduct, indexOfLastProduct);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
useEffect(() => {
const fetchData = async () => {
const result = await axios.get(
`http://${api}/cart?limit=${PRODUCTSPERPAGE}&offset=${
(currentPage - 1) * 3 + 1
}`,
{
headers: { Authorization: localStorage.getItem("token") },
}
);
setCurrentPage(currentPage);
};
fetchData();
}, [currentPage, productsPerPage]);
import React from "react";
import styled from "styled-components";
export default function Pagination({
productsPerPage,
paginate,
currentPage,
count,
}) {
const pageArrLength = Math.ceil(count / productsPerPage);
const pageNumber = Array(pageArrLength)
.fill(1)
.map((el, idx) => el + idx);
return (
<PageContainer currentPage={currentPage} className="pagination">
{pageNumber.map((pageNum) => (
<li
key={pageNum}
onClick={() => paginate(pageNum)}
>
{pageNum}
</li>
))}
</PageContainer>
);
}