First and foremost, we must establish a Laravel 8 application.
composer create-project laravel/laravel react-app
cd react-app
Back-End
Follow the instructions here to set up the back-end for Inertia.js.
composer require inertiajs/inertia-laravel
Create a Root template with the following contents in resources/views/app.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
<script src="{{ mix('/js/app.js') }}" defer></script>
</head>
<body>
@inertia
</body>
</html>
Create a route in routes/web.php
use Inertia\Inertia;
Route::get('home', function(){
return Inertia::render('home');
});
Note: We haven't constructed the Home component yet, which is specified in the render method.
Front-End
Let's get our front-end up and running by following the instructions provided.
We'll begin with a collection of installations:
npm i react-dom
npm install @inertiajs/inertia @inertiajs/inertia-react
npm i jsconfig.json
Initialize our Inertia app like below inside resources/js/app.js:
import { InertiaApp } from '@inertiajs/inertia-react'
import React from 'react'
import { render } from 'react-dom'
const app = document.getElementById('app')
render(
<InertiaApp
initialPage={JSON.parse(app.dataset.page)}
resolveComponent={name => import(`./pages/${name}`).then(module => module.default)}
/>,
app
)
Create our Home component at resources/js/pages/home.js
import React from "react";
const Home = () => {
let parameter1 = "React";
let parameter2 = "laravel 8";
return (
<h1>
Hello {parameter1} + {parameter2}
</h1>
);
};
export default Home;
Lets install babel/preset-react as dev dependency.
npm install --save-dev @babel/preset-react
Create a .babelrc file at root of our project with following contents:
{
"presets": ["@babel/preset-react"]
}
Test Our Project
npm run dev
php artisan serve
Latest comments (6)
It gives me 404.
"php artisan optimize" Run that on your project terminal.
I just did. Cleared cache successfully. I run
php artisan serve
again but still gives me the same 404. And when i go localhost:8000/home it gave me the error "Mix Manifest does not exist." So I had to includemix.js('resources/js/app.js', 'public/js').react()
in my webpack.mix.js file. I also went ahead and included webpack.config.js (though I don' know if this was necessary) and then runnpm run dev
. It worked finally when i used localhost:8000. I think you need to update the post and include that step.Ruan again 'npm run dev' on your project terminal.
Great blog! Thank you very much.
Thank you for sharing.