DEV Community

Navnit Rai
Navnit Rai

Posted on

pagination (forked)

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 (
    <div className="products">
      {/* 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 (
            <span className="products__single" key={prod.id}>
              {/* Display product thumbnail */}
              <img src={prod.thumbnail} alt={prod.title} />
              {/* Display product title */}
              <span>{prod.title}</span>
            </span>
          );
        })
      ) : (
        // If there are no products, display a loading message
        <p>Loading products...</p>
      )}
      {/* Display pagination controls if there are products */}
      {products.length > 0 && (
        <div className="pagination">
          {/* Left arrow for going to the previous page */}
          <span
            className={
              page > 1 ? "pagination__control" : "pagination__control--disabled"
            }
            onClick={() => selectPageHandler(page > 1 ? page - 1 : page)}
          >
            ⬅️
          </span>
          {/* Display page numbers */}
          {[...Array(Math.ceil(products.length / 10))].map((_, i) => {
            return (
              <span
                className={
                  page === i + 1
                    ? "pagination__selected"
                    : "pagination__control"
                }
                onClick={() => selectPageHandler(i + 1)}
                key={i}
              >
                {i + 1}
              </span>
            );
          })}
          {/* Right arrow for going to the next page */}
          <span
            className={
              page < Math.ceil(products.length / 10)
                ? "pagination__control"
                : "pagination__control--disabled"
            }
            onClick={() =>
              selectPageHandler(
                page < Math.ceil(products.length / 10) ? page + 1 : page
              )
            }
          >
            ➡️
          </span>
        </div>
      )}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)