Adding Pagination to a Next.js App
To enable users to navigate through different pages and view all invoices, implement pagination using URL parameters, similar to the search functionality.
Back to the Project
Step 1
- If you navigate to the
Pagination
component, you see that it is a client component. To avoid exposing database secrets, refrain from fetching data on the client side. Instead, fetch the data on the server and pass it as a prop to the component; - In
app/dashboard/invoices/page.tsx
, import a new function calledfetchInvoicesPages
and pass the search query fromsearchParams
as an argument:fetchInvoicesPages
calculates the total number of pages based on the search query. For instance, if there are 12 matching invoices with a display of 6 per page, the total number of pages would be 2.
- Pass the
totalPages
prop to the<Pagination/>
component.
Step 2
- Navigate to the
app/ui/invoices/pagination.tsx
; - Import the
usePathname
anduseSearchParams
hooks; - Use these hooks to retrieve the current page and set the new page;
- Uncomment the code in this component.
Note
Your application may temporarily break as the
<Pagination/>
logic is not yet implemented. We will work on it later.
Step 3
- Inside the
<Pagination>
component, create a new function calledcreatePageURL
; - Similar to the search functionality, utilize
URLSearchParams
to set the new page number; - Use
pathName
to construct the URL string; - Uncomment the
allPages
variable.
Step 4
Final step - when the user inputs a new search query, it's essential to reset the page number to 1. To achieve this, update the handleSearch
function in the app/ui/search.tsx
.
In Practice
Дякуємо за ваш відгук!