Set up Laravel Inertia with React and Vite in Laravel 10

How to set up Laravel Inertia with React and Vite in Laravel 10

Posted by Luke Beeno on May 7, 2023

Set up Laravel Inertia with React and Vite in Laravel 10

How to set up Laravel Inertia with React and Vite in Laravel 10

Posted by Luke Beeno on May 7, 2023

Laravel Inertia is a package that allows you to build single-page applications (SPAs) using Vue.js or React within a Laravel application. It provides a way to create dynamic, interactive user interfaces while leveraging the backend power and features of Laravel.

In traditional Laravel applications, when you navigate to a new page, the entire HTML page is refreshed, causing a full page reload. This can result in slower user experience and loss of application state. Inertia addresses this issue by using server-side rendering (SSR) for the initial page load and then utilizing JavaScript to handle subsequent updates and interactions, providing a smoother and more responsive user experience.

With Inertia, you can write your frontend components using Vue.js or React and communicate with the backend through a simple JavaScript object. It allows you to share the same validation, routing, and middleware between your frontend and backend, reducing duplication and improving development efficiency.

Inertia also integrates seamlessly with Laravel's authentication system, making it easy to handle user authentication and authorization within your SPA.

Overall, Laravel Inertia combines the power and convenience of Laravel's backend with modern JavaScript frameworks to create fast, dynamic, and interactive applications.

In this lesson we will be using React with Inertia.This lesson will not go through setting up react with Vite in Laravel 10. However, if you wish to know how to set up react with Vite, please go here https://wecode101.com/how-to-install-react-in-laravel-9-with-vite.

To set up Inertia in your Laravel 10 application, you'll need to follow a few steps:

1. Install the Inertia package: Inertia provides an official Laravel adapter package, so you can install it via Composer by running the following command in your terminal:

composer require inertiajs/inertia-laravel

2. Go to the blade file where you have Vite and insert Inertia

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Wecode101 Inertia</title>
    @viteReactRefresh
    @vite(['resources/sass/app.scss', 'resources/js/app.jsx'])
    @inertiaHead
</head>
<body>
    @inertia
</body>
</html>

2. Create a middleware for Inertia by running the following command in your terminal:

$ composer require inertiajs/inertia-laravel

In order to use the middleware go to the app/Http/Kernel.php file and add it to the web middleware group.

// ...
'web' => [
    // ...
    \App\Http\Middleware\HandleInertiaRequests::class,
],
// ...

3. Set up your routes: Define your application routes in the routes/web.php file. You'll need to define a route for the root URL that will serve as the entry point to your Inertia application. Here's an example:

use Inertia\Inertia;

Route::get('/', function () {
    return Inertia::render('Index');
});

4. Double check your vite.config.js file to ensure that it has the confiration below:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/sass/app.scss',
                'resources/js/app.jsx',
            ],
            refresh: true,
        }),
        react(),
    ],
});

5. Now, go to resources/js, rename app.js to app.jsx and configure it as below:

import React from 'react';
import {createRoot} from 'react-dom/client';
import {createInertiaApp } from '@inertiajs/inertia-react';
import {resolvePageComponent} from 'laravel-vite-plugin/inertia-helpers';
import 'bootstrap';
import axios from 'axios';

window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

createInertiaApp({
    resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`,import.meta.glob('./Pages/**/*.jsx')),
    setup({ el, App, props }) {
        createRoot(el).render(<App {...props} />)
    },
})

6. Create a Pages directory inside resources/js and create a component called Index.jsx:

import React, { useState } from 'react';

const Index = () => {
    return (
        <h1>Example Inertia SPA</h1>
    )
}

export default Index

7. Run the following command to compile your JavaScript assets:

npm run dev

That's it! You should now have Inertia set up in your Laravel application. You can start building your Inertia views and using Vue.js or React components within your Laravel app. Remember to run npm run dev or npm run watch to recompile your assets whenever you make changes.

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question