DEV Community

Leo Boissard
Leo Boissard

Posted on

🚀 Using ReactJS with Laravel!

Hi Everyone!

1 Let's create a new laravel project.

composer create laravel/laravel app
Enter fullscreen mode Exit fullscreen mode

2 Now we need to configure the server-side and client-side. First install InertiaJS, this is where the magic happens.

composer require inertiajs/inertia-laravel
Enter fullscreen mode Exit fullscreen mode
npm install @inertiajs/react
Enter fullscreen mode Exit fullscreen mode
  1. Create a root template file named app.blade.php, in resources/view folder. Put the flags @inertiaHead and @inertia, like this
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    @vite('resources/js/app.jsx')
    @inertiaHead
  </head>
  <body>
    @inertia
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Remember to rename resources/js/app.js to resources/js/app.jsx

4 Speaking of app.jsx, let's get edited.

import React from "react";
import { createInertiaApp } from "@inertiajs/react";
import { createRoot } from "react-dom/client";

createInertiaApp({
    resolve: (name) => {
        const pages = import.meta.glob("./Pages/**/*.jsx", { eager: true });
        return pages[`./Pages/${name}.jsx`];
    },
    setup({ el, App, props }) {
        createRoot(el).render(<App {...props} />);
    },
});
Enter fullscreen mode Exit fullscreen mode

5 Next we need to setup the Inertia middleware. Type this command.

php artisan inertia:middleware
Enter fullscreen mode Exit fullscreen mode

6 Let's register that middleware, go to app/Http/Kernel.php and put this as the last item in your "web" middleware group.

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

7 That's all! Create a file named Home.jsx at folder resources/js/Pages

export default function Home() {
    return (
        <h1>ReactJS with Laravel? Awesome!!</h1>    
    );
}
Enter fullscreen mode Exit fullscreen mode

8 Don't forget to edit the route file in laravel, routes/web.php

...
use Inertia\Inertia;

Route::get('/', function () {
    return Inertia::render('Home');
});
Enter fullscreen mode Exit fullscreen mode

I hope you enjoy, bye!
LB

Top comments (0)