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
Paginationcomponent, 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 calledfetchInvoicesPagesand pass the search query fromsearchParamsas an argument:fetchInvoicesPagescalculates 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
totalPagesprop to the<Pagination/>component.
Step 2
- Navigate to the
app/ui/invoices/pagination.tsx; - Import the
usePathnameanduseSearchParamshooks; - 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
URLSearchParamsto set the new page number; - Use
pathNameto construct the URL string; - Uncomment the
allPagesvariable.
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
すべて明確でしたか?
フィードバックありがとうございます!
セクション 6. 章 3
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 6. 章 3