Integrate ReactJS in Laravel
Tags: javascript, react, laravel
Published: 2021-10-28 09:44:51

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](https://inertiajs.com/) 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](https://laravel.com/docs/8.x/starter-kits#breeze-and-inertia) 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](https://laravel.com/docs/8.x/installation#installation-via-composer) to create a new Laravel project. Type the following command in your favourite terminal:

```
laravel new laravel-react
```
Now we need to get into the project:

```
cd laravel-react
```

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](https://inertiajs.com/server-side-setup) for more information:

```
composer require inertiajs/inertia-laravel
```

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

```
php artisan inertia:middleware
```

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

```php
'web' => [
  // ...
  \App\Http\Middleware\HandleInertiaRequests::class,
],
```

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

```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>
    @inertiaHead
  </head>
  <body>
    @inertia
  </body>
</html>
```

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

```php
Route::get('/', function () {
   return inertia('Welcome');
}
```

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](https://nodejs.org/en/download/) explains this in detail. In your terminal, type the following command:

```
npm i @inertiajs/inertia @inertiajs/inertia-react react-dom jsconfig.json @inertiajs/progress
```

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
```
Create a .babelrc file in the root directory of our project and paste the following code:

```javascript
{
    "presets": ["@babel/preset-react"]
}
```

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

```jsx
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)
  },
})
```

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:

```javascript
mix.js('resources/js/app.js', 'public/js')
    .react() //* Include this
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
```

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:

```jsx
import React from 'react'

export default function Welcome () {
    return (
        <>
            <div>Hello Inertia!</div>
        </>
    );
}
```

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!