composer create-project laravel/laravel example-app
cd example-app
composer require inertiajs/inertia-laravel
Rename file resources/app/welcome.blade.php to the app.blade.php and paste the next code inside:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
@inertiaHead
@viteReactRefresh
@vite(['resources/css/app.css', 'resources/js/app.jsx'])
<!-- As you can see, we will use vite with jsx syntax for React-->
@inertiaHead
</head>
<body>
@inertia
</body>
</html>
After that we need to generate a middleware for Inertia by using the next command:
php artisan inertia:middleware
And to use the middleware that we just generated, open the app/Http/Kernel.php file and go to the web middleware group and add generated middleware to the web group:
'web' => [
// ...
\App\Http\Middleware\HandleInertiaRequests::class,
],
Client-side setup
Before we are going to write a first React component — we need to install all dependencies that we need for this tutorial:
npm install @inertiajs/inertia-react @inertiajs/react @vitejs/plugin-react react react-dom
After installation, we will need to configure Vite in our application so let’s do this in vite.config.js:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react(), // React plugin that we installed for vite.js
laravel({
input: ['resources/css/app.css', 'resources/js/app.jsx'],
refresh: true,
}),
],
});
Okay, and now we can configure the app.js file, but first let’s rename this file to the app.jsx:
import './bootstrap';
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} />)
},
})
ow we need to create a “Pages” folder inside the js folder, and inside this folder let’s create a test component named “Test.jsx”:
const Test = () => {
return (
<h1>This is test component</h1>
)
}
export default Test
Render component
We configured everything that we need to use React in our application and now it’s time to render the component that we just created, so let’s open routes/web.php and let’s try to render Test.jsx on the homepage:
use Illuminate\Support\Facades\Route;
use Inertia\Inertia; // We are going to use this class to render React components
Route::get('/', function () {
return Inertia::render('Test'); // This will get component Test.jsx from the resources/js/Pages/Test.jsx
});
Okay, and the final step — run the local server and run vite in the terminal:
php artisan serve
npm run dev
---------------------------------------------------------------------------
Reference links
No comments:
Post a Comment