Making Paginations with React and TypeScript
In this article, I will show you how to create a pagination in your React and Typescript app. We will be building a blog with the post data being fetched from JSONPlaceholder.
But first
What is pagination and why do we use it?
To keep things simple, pagination is a way of splitting large amounts of information into smaller, easier to manage chunks, typically displayed across multiple pages.
We use pagination to
Now that we know what pagination is, lets build our own!
Note: Due to the scope of the article, I'll only strictly speak on the pagination logic. I won't be covering how I made my custom components or hooks. However, the code is available to view in the accompanying live demo.
Starting Setup
Here is what we're starting with
At this point, you should see 100 posts on the page.
Creating The Dropdown To Specify Amount Of Posts Per Page
Now we need to figure out a way to specify how many posts to show.
First, we create a state to store the itemsPerPage value using useState.
Then we create an array to store the options for the numbers per page.
We then create a Dropdown that renders the options and updates the itemsPerPage value when an option is selected.
Creating the pagination
Before creating the custom Pagination component, we first have to create some variables for it to use
We then also create a paginate variable that simply updates the currentPage value.
We can now finally create our Pagination component.
Here is the final code with the Pagination component
Consider this: while the current solution is effective for managing smaller datasets, imagine the impact of fetching thousands of entries at once. Not only does this lead to potential slowdowns, but it also results in a subpar user experience. A more efficient approach would involve fetching only the posts required for the current page, rather than loading everything at once. This not only enhances performance but also ensures a smoother browsing experience for users.
Here is the full live demo in action
Let me know what think and what other topics to cover in my article!
Director - India Operations at Aricord Consulting Limited | SAP FICO Consultant | Expert in SAP AP, Cloud Migrations | Trained in SAP TRM & Group Reporting | Contact: kalai.vani@aricord.com | +91 8015629340 |
10moMy cousin Looking for Pagination job - 12 + yrs experience expected ctc - 4 L per year contact +91 8015629340