From dcf43ec50856ceaf4d434df148532bc72f873cb1 Mon Sep 17 00:00:00 2001 From: haraldnilsen Date: Mon, 4 Sep 2023 15:49:18 +0200 Subject: [PATCH] :sparkles: implemented pagination component Co-authored-by: Sindre Kjelsrud --- src/App.tsx | 5 +++++ src/components/Pagination/index.tsx | 27 ++++++++++++++++++----- src/components/PaginationButton/index.tsx | 11 +++++++-- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index e510dbb..b5dc10f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -26,6 +26,10 @@ function App() { return Math.round(totalResults / 10) } + const handlePageChange = (pageNumber: number) => { + setCurrentPage(pageNumber) + } + return ( <> @@ -35,6 +39,7 @@ function App() { )} diff --git a/src/components/Pagination/index.tsx b/src/components/Pagination/index.tsx index 53725d6..c8c74cc 100644 --- a/src/components/Pagination/index.tsx +++ b/src/components/Pagination/index.tsx @@ -5,9 +5,14 @@ import { useEffect, useState } from 'react' interface PaginationProps { currentPage: number totalPages: number + handlePageChange: (pageNumber: number) => void } -const Pagination: React.FC = ({ currentPage, totalPages }) => { +const Pagination: React.FC = ({ + currentPage, + totalPages, + handlePageChange, +}) => { const [showLeftDots, setShowLeftDots] = useState(false) const [showRightDots, setShowRightDots] = useState(false) const [showingNumbers, setShowingNumbers] = useState([0]) @@ -15,8 +20,9 @@ const Pagination: React.FC = ({ currentPage, totalPages }) => { useEffect(() => { if (totalPages > 5) { setShowLeftDots(currentPage > 4 ? true : false) - setShowRightDots(currentPage < totalPages - 4 ? true : false) + setShowRightDots(currentPage < totalPages - 3 ? true : false) } + console.log('hei') if (!showLeftDots && !showRightDots) { setShowingNumbers(Array.from(Array(totalPages).keys())) } @@ -37,7 +43,7 @@ const Pagination: React.FC = ({ currentPage, totalPages }) => { if (showLeftDots && showRightDots) { setShowingNumbers([currentPage - 1, currentPage, currentPage + 1]) } - }, []) + }, [totalPages, currentPage, showLeftDots, showRightDots]) return ( @@ -45,20 +51,29 @@ const Pagination: React.FC = ({ currentPage, totalPages }) => { {showLeftDots && ( - + ... )} {showingNumbers.map((page) => ( - + ))} {showRightDots && ( ... - {' '} + {' '} )} diff --git a/src/components/PaginationButton/index.tsx b/src/components/PaginationButton/index.tsx index 51ef914..7b8263c 100644 --- a/src/components/PaginationButton/index.tsx +++ b/src/components/PaginationButton/index.tsx @@ -2,11 +2,18 @@ import q from 'qjuul' interface PaginationButtonProps { pageNumber: number + handlePageChange: (pageNumber: number) => void } -const PaginationButton: React.FC = ({ pageNumber }) => { +const PaginationButton: React.FC = ({ + pageNumber, + handlePageChange, +}) => { return ( - + handlePageChange(pageNumber)} + className="bg-red-400 p-2 rounded-md" + >

{pageNumber}

)