Skip to content

Commit e7f4088

Browse files
authored
Created sample-pagination
1 parent e77f917 commit e7f4088

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

sample-pagination

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import React, { useEffect, useState } from 'react';
2+
import './App.css';
3+
4+
export default function App() {
5+
const [data, setData] = useState([]);
6+
const [currentPage, setPerPage] = useState(1);
7+
8+
const itemsPerPage = 10;
9+
10+
const fetchProductData = async () => {
11+
const fetchResponse = await fetch(
12+
'https://dummyjson.com/products?limit=100'
13+
);
14+
const resp = await fetchResponse.json();
15+
console.log(resp);
16+
17+
if (resp && resp.products) {
18+
setData(resp.products);
19+
}
20+
};
21+
22+
useEffect(() => {
23+
fetchProductData();
24+
}, []);
25+
26+
const selectedPageProducts = (seletedPage) => {
27+
if (
28+
seletedPage >= 1 &&
29+
seletedPage <= data.length / 10 &&
30+
seletedPage !== currentPage
31+
) {
32+
setPerPage(seletedPage);
33+
}
34+
};
35+
36+
return (
37+
<div className="App">
38+
<div className="products">
39+
{data
40+
.slice(
41+
currentPage * itemsPerPage - itemsPerPage,
42+
currentPage * itemsPerPage
43+
)
44+
.map((item) => {
45+
return (
46+
<span className="products-card" key={item.id}>
47+
<img src={item.thumbnail} alt={item.images[1]} />
48+
<h1 className="product-title">{item.title}</h1>
49+
</span>
50+
);
51+
})}
52+
</div>
53+
{data.length > 0 && (
54+
<div className="pagination">
55+
<button
56+
onClick={() => selectedPageProducts(currentPage - 1)}
57+
className="prev"
58+
>
59+
◀️
60+
</button>
61+
{[...Array(data.length / itemsPerPage)].map((_, index) => {
62+
return (
63+
<button
64+
className={currentPage === index + 1 ? 'active' : ''}
65+
onClick={() => selectedPageProducts(index + 1)}
66+
key={index}
67+
>
68+
{index + 1}
69+
</button>
70+
);
71+
})}
72+
<button
73+
onClick={() => selectedPageProducts(currentPage + 1)}
74+
className="next"
75+
>
76+
▶️
77+
</button>
78+
</div>
79+
)}
80+
</div>
81+
);
82+
}
83+
84+
// export default App;

0 commit comments

Comments
 (0)