DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Integrate ReactJS in Laravel
Emokor Steven
Emokor Steven

Posted on • Updated on

Integrate ReactJS in Laravel

Now more than ever, it has become very easy to integrate React in your Laravel project, as opposed to before when one had to depend on APIs to connect the two stacks. This meant two different hosting environments and two Git repos to manage. But with InertiaJS we can build SPAs (single page apps) with your preferred front-end in one single project without need for APIs. Inertia has support for React, Vue or Svelte to use in your front-end. You pass data in your controllers as in any ordinary Laravel project, only difference is you're now rendering your views as JavaScript elements instead of blade. This can be done in two ways:

  • Using a starter kit like Laravel Breeze or Jetstream (which is a bit more tedious)
  • From scratch using npm and InertiaJS

In February 2021, Taylor Otwell (creator of Laravel) released InertiaJS version of Laravel Breeze. The Laravel documentation explains this in detail if you prefer using a starter kit.

However, in this short tutorial we will be focusing on option 2 which is creating the project from scratch using InertiaJS and npm. With Inertia, we shall have separate code bases but beautifully synced in one project. No need for APIs. Imagine Inertia as the glue between your front-end and your back-end.

Setting up the back-end

We need to first setup the back-end by creating a new laravel project and installing inertia using composer. You must have Laravel installed globally on your local machine, or you could just use composer to create a new Laravel project. Type the following command in your favourite terminal:

laravel new laravel-react
Enter fullscreen mode Exit fullscreen mode

Now we need to get into the project:

cd laravel-react
Enter fullscreen mode Exit fullscreen mode

We need to install inertia into our new project because inertia will do the job of helping our front-end speak to our back-end. You can refer to the InertiaJS documentation for more information:

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

In your terminal, type the following command to create a middleware to power up inertia:

php artisan inertia:middleware
Enter fullscreen mode Exit fullscreen mode

Then head to your app/Http/Kernel.php file and add the following in $middlewareGroups section, as the last line:

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

Now let's head to our project directory in resources/views/ and create a new file app.blade.php and paste the following code:

<!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>
    @inertiaHead
  </head>
  <body>
    @inertia
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Finally, let us create the route for our welcome page. Go to routes/web.php and modify the route as below:

Route::get('/', function () {
   return inertia('Welcome');
}
Enter fullscreen mode Exit fullscreen mode

or you could simply use return Inertia::render('Welcome') and include the line use Inertia\Inertia below the namespace declaration to add the inertia class in your web.php file.

And that's pretty much it for the back-end setup.

Setting up the front-end

We are using npm to install our front-end dependencies. So you need to have npm installed on your local machine to have it smooth. The NodeJS documentation explains this in detail. In your terminal, type the following command:

npm i @inertiajs/inertia @inertiajs/inertia-react react-dom jsconfig.json @inertiajs/progress
Enter fullscreen mode Exit fullscreen mode

The above instructions install the inertia-react dependencies, react-dom that helps us use the react stack, the inertia progress-bar effect for our page loading and the jsconfig.json file that identifies our project as one that is going to use JavaScript to render our views.

Once the dependencies have been installed, we need to install another important dependency that will help us compile all our JavaScript files, including our app.js file as the react root:

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

Create a .babelrc file in the root directory of our project and paste the following code:

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

Then go to resources/js/app.js and include the following code:

import React from 'react'
import { render } from 'react-dom'
import { createInertiaApp } from '@inertiajs/inertia-react'
import { InertiaProgress } from '@inertiajs/progress'

InertiaProgress.init()

createInertiaApp({
  resolve: name => require(`./Pages/${name}`),
  setup({ el, App, props }) {
    render(<App {...props} />, el)
  },
})
Enter fullscreen mode Exit fullscreen mode

Almost there. We then need to tell our webpack.mix.js file that we are using react in our project. So, let's include .react() in our mix.js() block of code:

mix.js('resources/js/app.js', 'public/js')
    .react() //* Include this
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
Enter fullscreen mode Exit fullscreen mode

We need to create our welcome page. Go to your resources/js/ directory and create a folder named Pages. Inside the Pages folder, create a Welcome.jsx file and include the following code:

import React from 'react'

export default function Welcome () {
    return (
        <>
            <div>Hello Inertia!</div>
        </>
    );
}
Enter fullscreen mode Exit fullscreen mode

Finally, run npm run dev or npm run watch in your terminal. When mix has finished running, then serve your Laravel project php artisan serve.
You should see "Hello Inertia" in your browser.

And that's pretty much it. Now, time to play!

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await