Make pagination with Reactjs

Abdullah Al Hommada
4 min readJun 16, 2023

This article consist of two parts, the first is how to make pagination with Reactjs components, and the second is how to make usePagination hook.

Let’s begin with the first part, so to implement pagination for a list of blog articles in a React functional component, you can follow these steps:

  • 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:
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
  • 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:
const totalPages = Math.ceil(items.length / itemsPerPage);
  • Define a function to handle the page change. This function will update the current page in the state.
const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};
  • 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.
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const displayedItems = items.slice(startIndex, endIndex);
  • Render the displayed items and a pagination component that allows the user to navigate to…

--

--

Abdullah Al Hommada

Full Stack Web Developer with a great passion for creating beautiful projects. aalhommada.com