Creating Pagination with Laravel and React Using Inertia.
js
Integrating Laravel and React with [Link] provides a modern full-stack application
framework that is both powerful and efficient. In this article, we will explore how to
implement pagination in React using Laravel's built-in pagination features.
Backend: Laravel
On the Laravel side, we create a PostController that handles fetching and paginating the data
in the index method:
use App\Models\Post;
use Inertia\Inertia;
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->paginate(10); // Paginate with 10 items per page
return inertia('Home', ['posts' => $posts]); // Pass data to the React
component
}
}
The route definition for this method is as follows:
Route::get('posts', [PostController::class, 'index']);
This setup uses Laravel's integration with [Link] to send data as JSON to the frontend
without requiring a full-page reload.
Frontend: React
The React component receives the data from Laravel and displays it to the user. Below is an
example of rendering a Post list and pagination links:
import React from "react";
import { Link } from "@inertiajs/react";
export default function Home({ posts }) {
const postData = [Link] || [];
return (
<>
<h1 className="title">Post List</h1>
<table></table>
<div className="pagination-container py-12 px-4 flex justify-center mt-4">
{[Link]((link) =>
[Link] ? (
<Link
key={[Link]}
href={[Link]}
className={`pagination-link mx-1 px-3 py-1.5 border rounded-md ${
[Link]
? "bg-blue-900 text-white"
: "bg-white text-blue-900 border-blue-900"
} hover:bg-blue-900 hover:text-white`}
dangerouslySetInnerHTML={{ __html: [Link] }}
/>
) : (
<span
key={[Link]}
className={`pagination-link mx-1 px-3 py-1.5 border rounded-md`}
dangerouslySetInnerHTML={{ __html: [Link] }}
/>
))}
</div>
</>
);
}
Key Points:
1. Formatting Dates:
- We use new Date() to format dates into a readable format.
- Alternatively, libraries like date-fns or [Link] can be used for more advanced
formatting.
2. Styling with Tailwind:
- To simplify managing CSS classes, you can use libraries like clsx or classnames.
Conclusion
By combining Laravel and React with [Link], we created a seamless and modern full-stack
application. Laravel’s robust backend and React’s flexible frontend make the development
process both efficient and enjoyable.