How To Install React in Laravel 9 with Vite
Tags: laravel, react, javascript, webdev
Published: 2022-07-14 04:40:40


Laravel has just released **_“laravel 9.19”_** with a major change. There is no more webpack.mix.js file in the laravel root in the place of the **_webpack.mix.js_** file **_vite.config.js_** file is introduced.

In this post, we will learn how to install React js 3 in laravel 9.19 with vite ?. This post shows you how to install React in laravel 9 with the latest upgrades. If you want to see an example of **installing react 3 in laravel-vite** then you are in the right place. Laravel 9.19 with vite is the latest version of the laravel framework at the writing of this article. As you know Laravel is the most popular PHP framework and it’s easy to use scale, and flexible.

React is an open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

By the end of this post, you’ll be able to create a React and Laravel 9.19 application powered by vite. We’ll also learn how to create a react component and connect it with laravel 9 blade file.

## How To Install React in Laravel 9 with Vite

Use the following steps to install React in the laravel 9 application.

1.  Install laravel 9 App
    
2.  Install NPM Dependencies
    
3.  Install React
    
4.  Install vitejs/plugin-react plugin
    
5.  Update vite.config.js
    
6.  Vite Dev Server Start
    
7.  Create Reactjs Component
    
8.  Update app.js file in resources folder
    
9.  Create Custom Helper For Vite Assets
    
10.  Connect Reactjs Component with Laravel blade file
    
11.  Update .env file
    
12.  Start The Local Server
    

### Step 1: Install laravel 9 App

First, open Terminal and run the following command to create a fresh laravel project:

```bash
composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-react-vite
```

or, if you have installed the Laravel Installer as a global composer dependency:

```bash
laravel new laravel9-react-vite
```

### Step 2: Install NPM Dependencies

Run the following command to install frontend dependencies:

```bash
npm install
```

### Step 3: Install React

Now after installing node modules we need to install reactjs in our application, for that execute the following command in the terminal **_npm install  react@latest  react-dom@latest_**. It will install latest version of reactjs and react-dom also. we’ll use it in **_jsx_** file.

```bash
npm install react@latest react-dom@latest
```

### Step 4: Install vitejs/plugin-react plugin

In laravel 9 latest release install vitejs/plugin-react plugin for installing reactjs in laravel. This plugin provides required dependencies to run the reactjs application on vite. Vite is a build command that bundles your code with Rollup and it runs on localhost:3000 port to give hot refresh feature.

```bash
npm i @vitejs/plugin-react --force
npm i @vitejs/plugin-react-refresh --force
```

### Step 5: Update vite.config.js file

The latest 9.19 Provides a vite.config.js file in the root of the application to configure front-end assets preset import plugin-react and add react() to the plugins array in the defineConfig() function.

```javascript
import reactRefresh from '@vitejs/plugin-react-refresh';


export default ({ command }) => ({
    base: command === 'serve' ? '' : '/build/',
    publicDir: 'fake_dir_so_nothing_gets_copied',
    build: {
        manifest: true,
        outDir: 'public/build',
        rollupOptions: {
            input: 'resources/js/app.js',
        },
    },
    plugins: [
        reactRefresh(),
    ],
});
```

### Step 6: Vite Dev Server Start

Now after installing the reactjs, we need to start the dev server for vite for that run the following command and it will watch your **_resources/js/app.js_** file and **_resources/css/app.css_** file. It also starts a vite server on http://localhost:3000. you can not open it in the browser as it is for vite hot reload and it runs in the background and watches the assets of your application like js and CSS.

```bash
npm run dev
```

### Step 7: Create Reactjs Component

Under the **resources/js** folder create a file name **_App.jsx_** and write content for this example let’s write simple “Reactjs With Laravel Vite” you can change it according to your requirement.

```javascript
// resources/js/App.jsx
import React from 'react';
import { createRoot } from 'react-dom/client'

export default function App(){
    return(
        <h1>How To Install React in Laravel 9 with Vite</h1>
    );
}

if(document.getElementById('root')){
    createRoot(document.getElementById('root')).render(<App />)
}
```

### Step 8: Update app.js file in resources folder

In **_resources/js/app.js_** Import App.jsx component

```javascript
// resources/js/app.js
import './bootstrap';

import './App.jsx'
```

### Step 9: Create Custom Helper For Vite Assets

To work around this, we can ping `localhost:3000`. If it connects, we know the dev server is running and we can render the hot scripts.

This could go in a `helpers.php` file, learn how to set one up [here](https://techvblogs.com/blog/how-to-create-custom-helper-functions-in-laravel).

First, let’s extract the code we had written in our Blade template to a helper function. Next, we’ll use Laravel `Http` facade to ping `localhost:3000`. If it connects, we know the dev server is running.

```php
<?php

use Illuminate\Support\Facades\Http;
use Illuminate\Support\HtmlString;

function vite_assets(): HtmlString
{
    $devServerIsRunning = false;
    
    if (app()->environment('local')) {
        try {
            Http::get("http://localhost:3000");
            $devServerIsRunning = true;
        } catch (Exception) {
        }
    }
    
    if ($devServerIsRunning) {
        return new HtmlString(<<<HTML
            <script type="module" src="http://localhost:3000/@vite/client"></script>
            <script type="module" src="http://localhost:3000/resources/js/app.js"></script>
        HTML);
    }
    
    $manifest = json_decode(file_get_contents(
        public_path('build/manifest.json')
    ), true);
    
    return new HtmlString(<<<HTML
        <script type="module" src="/build/{$manifest['resources/js/app.js']['file']}"></script>
        <link rel="stylesheet" href="/build/{$manifest['resources/js/app.js']['css'][0]}">
    HTML);
}
```

### Step 10: Connect Reactjs Component with Laravel blade file

Now we need to create a blade file where the reactjs app will load. In the **resources/views** folder open a file name _**welcome.blade.php**_. Add **_@vite(‘resources/js/app.js’)_** at the bottom of the file in the react.blade.php file It will load all the js you need to run the Reactjs code.

```html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>How To Install React in Laravel 9 with Vite</title>

    {{ vite_assets() }}
</head>
<body>
	<div id="root"></div>
</body>
</html>
```

### Step 11: Update .env file

Open .env file and update **APP_URL** and set APP_URL=http://localhost:8000. It will help vite to check the js and CSS updates and changes them in the browser instantly.

```
APP_URL=http://localhost:8000
```

### Step 12: Start the Local server

Start the development server

```bash
php artisan serve
```

and navigate to the following link [http://localhost:8000/](http://localhost:8000/)

**Thank you** for reading this blog.

You can find the GitHub repository here [suresh-ramani/laravel-react-vite](https://github.com/suresh-ramani/laravel-react-vite).