Hi Everyone!
1 Let's create a new laravel project.
composer create laravel/laravel app
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
npm install @inertiajs/react
- Create a root template file named
app.blade.php
, inresources/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>
Remember to rename
resources/js/app.js
toresources/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} />);
},
});
5 Next we need to setup the Inertia middleware. Type this command.
php artisan inertia:middleware
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,
],
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>
);
}
8 Don't forget to edit the route file in laravel, routes/web.php
...
use Inertia\Inertia;
Route::get('/', function () {
return Inertia::render('Home');
});
I hope you enjoy, bye!
LB
Top comments (0)