| 1 | |
| 2 | import { useEffect, useState } from "react" |
| 3 | import data from "../../util/blog.json" |
| 4 | import BlogCard1 from "./BlogCard1" |
| 5 | import Pagination from "./Pagination" |
| 6 | export default function BlogPost({ style, showItem, showPagination }) { |
| 7 | let [currentPage, setCurrentPage] = useState(1) |
| 8 | let showLimit = showItem, |
| 9 | paginationItem = 4 |
| 10 | |
| 11 | let [pagination, setPagination] = useState([]) |
| 12 | let [limit, setLimit] = useState(showLimit) |
| 13 | let [pages, setPages] = useState(Math.ceil(data.length / limit)) |
| 14 | |
| 15 | useEffect(() => { |
| 16 | cratePagination() |
| 17 | }, [limit, pages, data.length]) |
| 18 | |
| 19 | const cratePagination = () => { |
| 20 | |
| 21 | let arr = new Array(Math.ceil(data.length / limit)) |
| 22 | .fill() |
| 23 | .map((_, idx) => idx + 1) |
| 24 | |
| 25 | setPagination(arr) |
| 26 | setPages(Math.ceil(data.length / limit)) |
| 27 | } |
| 28 | |
| 29 | const startIndex = currentPage * limit - limit |
| 30 | const endIndex = startIndex + limit |
| 31 | const getPaginatedProducts = data.slice(startIndex, endIndex) |
| 32 | |
| 33 | |
| 34 | let start = Math.floor((currentPage - 1) / paginationItem) * paginationItem |
| 35 | let end = start + paginationItem |
| 36 | const getPaginationGroup = pagination.slice(start, end) |
| 37 | |
| 38 | const next = () => { |
| 39 | setCurrentPage((page) => page + 1) |
| 40 | } |
| 41 | |
| 42 | const prev = () => { |
| 43 | setCurrentPage((page) => page - 1) |
| 44 | } |
| 45 | |
| 46 | const handleActive = (item) => { |
| 47 | setCurrentPage(item) |
| 48 | } |
| 49 | return ( |
| 50 | <> |
| 51 | |
| 52 | |
| 53 | {getPaginatedProducts.length === 0 && ( |
| 54 | <h3>No Products Found </h3> |
| 55 | )} |
| 56 | |
| 57 | {getPaginatedProducts.map((item, i) => ( |
| 58 | <BlogCard1 key={i} item={item} /> |
| 59 | ))} |
| 60 | |
| 61 | {showPagination && |
| 62 | <Pagination |
| 63 | getPaginationGroup={ |
| 64 | getPaginationGroup |
| 65 | } |
| 66 | currentPage={currentPage} |
| 67 | pages={pages} |
| 68 | next={next} |
| 69 | prev={prev} |
| 70 | handleActive={handleActive} |
| 71 | /> |
| 72 | } |
| 73 | </> |
| 74 | ) |
| 75 | } |