React - rendering pagination numbers with ellipsis (with JSON data)

0 votes
169 views
added May 16 in React by lcjr First Warrant Officer (11,760 points)
edited May 16 by lcjr
import React, { useState, useEffect } from 'react';

const TestPagiComponent = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      const res = await fetch('https://jsonplaceholder.typicode.com/posts');
      const result = await res.json();
      setData(result);
      setLoading(false);
    };

    fetchData();
  }, []);

  // Get current items
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);

  // Change page
  const paginate = (pageNumber, event) => {
    event.preventDefault();
    setCurrentPage(pageNumber);
  };

  // Get page numbers
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(data.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }

  // Logic for rendering pagination numbers with ellipsis
  const renderPageNumbers = () => {
    let renderPages = [];

    if (pageNumbers.length <= 5) {
      renderPages = pageNumbers;
    } else {
      if (currentPage <= 3) {
        renderPages = [...pageNumbers.slice(0, 3), '...', pageNumbers.length];
      } else if (currentPage >= pageNumbers.length - 2) {
        renderPages = [1, '...', ...pageNumbers.slice(pageNumbers.length - 3)];
      } else {
        renderPages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', pageNumbers.length];
      }
    }

    return renderPages.map((number) =>
      number === '...' ? (
        <span key={number} style={{ padding: '5px 10px', border: 'none', cursor: 'default' }}>
          ...
        </span>
      ) : (
        <a
          key={number}
          onClick={(e) => paginate(number, e)}
          href="!#"
          style={{
            padding: '5px 10px',
            // border: '1px solid #2056AB',
            color: currentPage === number ? 'white' : '#2056AB',
            backgroundColor: currentPage === number ? '#2056AB' : 'transparent',
            textDecoration: 'none',
            cursor: 'pointer',
            margin: '0 6px',
            width: '39px',
            borderRadius: '3px',
          }}
        >
          {number}
        </a>
      )
    );
  };

  if (loading) {
    return <h2>Loading...</h2>;
  }

  return (
    <div>
      <ul style={{ listStyleType: 'none', padding: 0, margin: 0 }}>
        {currentItems.map((item) => (
          <li
            key={item.id}
            style={{
              border: '1px solid #ddd',
              padding: '10px',
              margin: '5px 0',
            }}
          >
            {item.title}
          </li>
        ))}
      </ul>
      <nav>
        <ul style={{ display: 'flex', justifyContent: 'center', listStyleType: 'none', padding: 0 }}>
          {renderPageNumbers()}
        </ul>
      </nav>
    </div>
  );
};

export default TestPagiComponent;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...