برنامه نویسی
صفحه بندی (چنگال شده) – انجمن DEV

import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
// State to hold the list of products
const [products, setProducts] = useState([]);
// State to hold the current page number
const [page, setPage] = useState(1);
// Function to fetch products from the API
const fetchProducts = async () => {
// Make a GET request to the API
const res = await fetch("https://dummyjson.com/products?limit=100");
// Parse the JSON response
const data = await res.json();
// Update the products state with the data from the API
setProducts(data.products);
};
// useEffect to fetch products when the component mounts
useEffect(() => {
fetchProducts();
}, []); // Empty dependency array means this runs only once, like componentDidMount
// Function to handle page selection
const selectPageHandler = (selectedPage) => {
// Update the page state with the selected page number
setPage(selectedPage);
};
return (
{/* If there are products, display them */}
{products.length > 0 ? (
// Slice the products array to display only 10 products per page
products.slice(page * 10 - 10, page * 10).map((prod) => {
return (
{/* Display product thumbnail */}
{/* نمایش عنوان محصول */}
{prod.title}
) }) ): ( // اگر محصولی وجود ندارد، پیام بارگیری را نمایش دهید
در حال بارگیری محصولات...
)} {/* در صورت وجود محصولات، کنترلهای صفحهبندی را نمایش دهید */} {products.length > 0 && (
{/* پیکان چپ برای رفتن به صفحه قبل */}
1 "صفحه بندی__کنترل" : "pagination__control--غیرفعال شد"
} onClick={() => selectPageHandler(صفحه > 1 ? صفحه - 1 : صفحه)} > ⬅️
{/* نمایش شماره صفحه */} {[...Array(Math.ceil(products.length / 10))].map((_, i) => { return (
selectPageHandler(i + 1)} key={i} > {i + 1}
) })} {/* پیکان سمت راست برای رفتن به صفحه بعد */}
selectPageHandler( page < Math.ceil(products.length / 10) ? page + 1 : page ) } > ➡️
)}
) }