How to Use Inertia Links in Laravel 11 with React

In the world of modern web development, creating seamless, responsive user interfaces is crucial. When working with Laravel 11 and React, Inertia.js provides an elegant solution for building single-page applications without the complexity of a full JavaScript framework. One of the key components in this ecosystem is the Inertia `Link` component. Let’s dive into how to use it effectively in your projects.

Laravel 11 Inertia CRUD with React TypeScript Example

What is Inertia Link?

The Inertia Link component is a powerful tool that replaces standard <a> tags in your React components. It enables client-side navigation while maintaining the simplicity of server-side routing. This means you get the best of both worlds: the smooth, fast experience of a single-page application with the straightforward routing of a traditional server-rendered app.

First, make sure you have Inertia.js set up in your Laravel 11 project with React. Then, in your React component, import the `Link` component:

import { Link } from '@inertiajs/react'

<Link href="/">Home</Link>

Dynamic URLs

You can easily create dynamic links using template literals:

<Link href={`/users/${user.id}`}>{user.name}</Link>

Custom HTTP Methods

Inertia Link supports all HTTP methods, not just GET:

import { Link } from '@inertiajs/react'

<Link href="/logout" method="post" as="button" type="button">Logout</Link>

// Renders as...
<button type="button">Logout</button>

State Preservation

To maintain component state across navigations, use the preserveState prop:

<Link href="/filter" preserveState>Apply Filter</Link>

Scroll Management

For long pages, you can preserve scroll position with preserveScroll:

<Link href="/page/2" preserveScroll>Next Page</Link>

Event Handling

Inertia Link provides various event hooks. Here’s an example using onBefore for confirmation:

<Link
  href="/delete-account"
  method="delete"
  onBefore={() => confirm('Are you sure?')}
>
  Delete Account
</Link>

Why Use Inertia Link?

  • Performance: Client-side navigation makes your app feel faster and more responsive.
  • Simplicity: You get SPA-like behavior without the complexity of managing a frontend router.
  • Security: CSRF tokens are automatically handled for non-GET requests.
  • Flexibility: Supports all HTTP methods and various customization options.
saim ansari
saim ansari

I'm Saim Ansari, a full-stack developer with 4+ years of hands-on experience who thrives on building web applications that leave a lasting impression. When it comes to tech, I'm particularly adept at Laravel, React, Tailwind CSS, and the Tall Stack