In this lesson, we will add pagination to our table. It won't be an easy one-minute process.
Modifying Controller for Pagination
app/Http/Controllers/TaskController.php
// ... public function index(){ return Inertia::render('Tasks/Index', [ 'tasks' => Task::all() 'tasks' => Task::paginate(5) ]);} // ...
Now, our Task List page will stop working because of a TypeScript structure mismatch. We return paginate() from Controller, which is no longer the array of the Task type. Let's fix this.
Creating Paginated Response Type
We return tasks from the Controller not as a list but as a paginated object.
So, we need to create a specific new type for it, corresponding to the structure returned by Laravel pagination.
resources/js/types/index.d.ts
// ... export interface PaginatedResponse<T = Task | null> { current_page: number; data: T[]; first_page_url: string; from: number; last_page: number; last_page_url: string; links: { url: string | null; label: string; active: boolean; }[]; next_page_url: string | null; path: string; per_page: number; prev_page_url: string | null; to: number; total: number;}
Accepting Paginated Response in React
In three places, we need to change the type of data we get.
- We import our new
PaginatedResponsetype - We use it in the
export functioninstead of...
The shadcn pagination component uses a regular
<a>tag for the links, so you'll notice that the pagination links cause a full page refresh. This can be remedied by updating the shadcn component to use the Inertia<Link>component.The great thing about shadcn and the way that the Laravel Starter Kits are implemented is that you can modify the components in this way, so no messy extending. Just be careful not to overwrite the changes later!
Thanks for the valuable comment, Joe, great notice!
That's a great point Joe however I just tried to naively update resources/js/components/ui/pagination.tsx to use "Link" instead of "a" and got myself into all sorts of trouble. Anyone got some hints or a Gist?
Yeah, it's pretty easy to break. I ended up enlisting the help of AI to do it. Here's what we came up with...
First import the inertia
<Link>at the top:Then redefine the
PaginationLinkPropstype slightly:Finally replace the
PaginationLinkfunction with this: