Laravel 8 with React(JS)

jsandaruwan

J-Sandaruwan

Posted on September 8, 2021

Laravel 8 with React(JS)

First and foremost, we must establish a Laravel 8 application.

composer create-project laravel/laravel react-app
cd react-app
Enter fullscreen mode Exit fullscreen mode

Back-End

Follow the instructions here to set up the back-end for Inertia.js.

composer require inertiajs/inertia-laravel
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Create a route in routes/web.php

use Inertia\Inertia;

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

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
Enter fullscreen mode Exit fullscreen mode

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
)
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Lets install babel/preset-react as dev dependency.

npm install --save-dev @babel/preset-react
Enter fullscreen mode Exit fullscreen mode

Create a .babelrc file at root of our project with following contents:

{
  "presets": ["@babel/preset-react"]
}
Enter fullscreen mode Exit fullscreen mode

Test Our Project

npm run dev

php artisan serve

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
jsandaruwan
J-Sandaruwan

Posted on September 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related