Make pagination with Reactjs

2023-02-19

To implement pagination for a list of blog articles in a React functional component, you can follow these steps:

  1. Define state variables to keep track of the current page and the number of items per page. You can do this using the useState hook, like so:
  2. const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);
    
  3. Calculate the total number of pages based on the number of items and the number of items per page. You can do this using the Math.ceil function, like so:
  4. const totalPages = Math.ceil(items.length / itemsPerPage);
    
  5. Define a function to handle the page change. This function will update the current page in the state.
  6. const handlePageChange = (pageNumber) => {
      setCurrentPage(pageNumber);
    };
    
  7. Use the slice method to display only the items for the current page. You can calculate the starting and ending indexes based on the current page and the number of items per page.
  8. const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const displayedItems = items.slice(startIndex, endIndex);
    
  9. Render the displayed items and a pagination component that allows the user to navigate to different pages. You can use the map method to generate the pagination links.
  10. return (
      <div>
        {displayedItems.map((item) => (
          // render each item here
        ))}
        <div className="pagination">
          {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNumber) => (
            <a
              key={pageNumber}
              onClick={() => handlePageChange(pageNumber)}
              className={pageNumber === currentPage ? "active" : ""}
            >
              {pageNumber}
            </a>
          ))}
        </div>
      </div>
    );
    

The pagination links are generated using the Array.from method to create an array with as many elements as the total number of pages. The map method is used to render each link as an anchor element. The className prop is used to apply the "active" class to the current page link. Finally, the onClick handler calls the handlePageChange function to update the current page in the state.