Skip to content

Commit 0dc2b66

Browse files
authored
feat(pagination): refactor pagination (kaliacad#224)
Fix kaliacad#221
1 parent 826a8c9 commit 0dc2b66

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

src/components/TopAfrica/TopAfrica.jsx

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ const TopAfrica = () => {
3030

3131
// Pagination states
3232
const [currentPage, setCurrentPage] = useState(1);
33-
const articlesPerPage = 6;
33+
const articlesPerPage = 9; // Display 9 or 12 items per page
3434

3535
const handleClicked = () => {
3636
setShowCard(!showCard);
@@ -83,14 +83,33 @@ const TopAfrica = () => {
8383
fetchDataForAllCountries();
8484
}, [date]);
8585

86-
// Pagination calculations
86+
// Calculate pagination values
8787
const indexOfLastArticle = currentPage * articlesPerPage;
8888
const indexOfFirstArticle = indexOfLastArticle - articlesPerPage;
8989
const currentArticles = data.slice(indexOfFirstArticle, indexOfLastArticle);
9090
const totalPages = Math.ceil(data.length / articlesPerPage);
9191

92+
// Handle pagination changes
9293
const paginate = (pageNumber) => setCurrentPage(pageNumber);
9394

95+
// Render page numbers for pagination
96+
const renderPageNumbers = () => {
97+
const pageNumbers = [];
98+
for (let i = 1; i <= totalPages; i++) {
99+
pageNumbers.push(
100+
<button
101+
key={i}
102+
onClick={() => paginate(i)}
103+
className={`px-2 py-1 mx-1 ${currentPage === i ? 'bg-blue-500 text-white' : 'bg-gray-300'}`}
104+
>
105+
{i}
106+
</button>,
107+
);
108+
}
109+
return pageNumbers;
110+
};
111+
112+
// Display loading component if data is loading
94113
if (loading)
95114
return (
96115
<div className='flex justify-center m-4 h-full items-center w-full'>
@@ -108,12 +127,7 @@ const TopAfrica = () => {
108127
Articles List/Article Gallery
109128
</button>
110129
<DatePicker onChange={handleChange} />
111-
<h1
112-
className='text-white
113-
'
114-
>
115-
Top Africa Atricle: {`${date.day}/${date.month}/${date.year}`}
116-
</h1>
130+
<h1 className='text-white'>Top Africa Article: {`${date.day}/${date.month}/${date.year}`}</h1>
117131
</div>
118132

119133
{loadingCard && !showCard && (
@@ -165,17 +179,15 @@ const TopAfrica = () => {
165179
disabled={currentPage === 1}
166180
className='px-4 py-2 bg-gray-300 rounded disabled:opacity-50'
167181
>
168-
Previous
182+
&larr;
169183
</button>
170-
<span className='text-lg text-white font-semibold'>
171-
Page {data.length == 0 ? 0 : currentPage} of {totalPages}
172-
</span>
184+
<div className='flex'>{renderPageNumbers()}</div>
173185
<button
174186
onClick={() => paginate(currentPage + 1)}
175187
disabled={currentPage === totalPages}
176188
className='px-4 py-2 bg-gray-300 rounded disabled:opacity-50'
177189
>
178-
Next
190+
&rarr;
179191
</button>
180192
</div>
181193
</div>

0 commit comments

Comments
 (0)