Install React in Laravel 9 with Vite
laramatic.om

Install React in Laravel 9 with Vite

Here is how to install React with Vite in Laravel 9 with just a few simple steps. 

Laravel 9.2.0

 Laravel has just released laravel 9.2 with four major changes that are aimed at making the web more user-friendly and scalable. The vite.config.js replaced webpack.mix.js recently in the previous upgrade so it’s likely we will see more changes during the Laravel 9.2.1 upgrade. 

In this post, we will learn how to install React js 3 in laravel 9.2 using vite with a complete walkthrough with examples. 

React was introduced by Facebook and its devs. It’s an open-source front-end JS library to build amazing UI. You can use React even as a base to develop a single page website or a mobile app. 

How To Install React in Laravel 9 with Vite

Use these steps to install React in the laravel 9: 

  1. Create a New Laravel 9 Project
  2. Install NPM Dependencies
  3. Install React
  4. Install vitejs/plugin-react plugin
  5. Update vite.config.js
  6. Start Vite Dev Server
  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

#1 Create a New Laravel 9 Project

Create a new Laravel 9 project in your terminal by using this command

composer create-project --prefer-dist laravel/laravel:^9.2 install-react-laravel9-vite

If Laravel 9 is already installed as a global composer then use this:

laravel new install-react-laravel9-vite

#2 Install NPM Dependencies

Run this command in your terminal to install npm dependencies:

npm install

#3 Install React

After installing the node package manager we are going to install reactjs in our project. Run npm install react@latest react-dom@latest. This will add the latest version of reactjs and react-dom that we will use in jsx. 

npm install react@latest react-dom@latest

#4 Install vitejs/plugin-react plugin

In order to install reactjs we need to install vitejs first in Laravel 9. It fulfills the need for the dependencies to run reactjs app with vite. 

npm i @vitejs/plugin-react --force

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

#5 Update vite.config.js file

The latest 9 upgrade has given us a vite.config.js file to use in our application root for configuring front-end assets preset import plugin-react and add react() to the plugins array in the defineConfig() function.

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(),
    ],
});

#6 Start Vite Dev Server

We will run the following command to start vite dev server that looks at our resources/js/app.js file and resources/css/app.css file. It starts vite server on http://localhost:3000. It runs in the background so we cannot access it through our browser as we use it for vite hot reload and it keep account of our app assets such as CSS and JS.

 npm run dev

#7 Create ReactJS Component

We need to create a file App.jsx under the resources/js folder and write the example contents on it such as Install ReactJS in Laravel 9 with Vite’ It can be changed however you want.

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

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

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

#8 Update app.js file in resources folder

In resources/js/app.js Import App.jsx component

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

import './App.jsx'

#9 Create Custom Helper For Vite Assets

We can render the hot scripts to the dev server to create a custom helper for Vite assets.First we have to ping localhost:3000 to make sure the dev server is running. 

This could go in a helpers.php file. 

We need to extract our Blade template code that we wrote to a helper function. Now we are going to use the Laravel Http facade to ping localhost:3000 to check dev server connectivity.

<?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);
}

#10 Connect ReactJS Component to The Laravel blade file

We have to help reactjs app load. To achieve that we will create a blade file where it can load. We will open a file welcome.blade.php from our resources/views folder. Then will add @vite(“resources/js/app.js”) at its end in our react.blade.php file. You will load all the js that is needed to run our ReactJS code in it. 

<!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>

#11 Update .env file

Next we have to navigate to our .env file and update APP_URL and set APP_URL=http://localhost:8000. This will let vite monitor JS and CSS changes whatever those might be and change them in a split second.

APP_URL=http://localhost:8000

#12: Start the Local server

Now finally we are done with each step of installing React in Laravel 9 with Vite. We need to start the dev server.

php artisan serve

Go to this link http://localhost:8000/

So this is how we can install Reactjs in Laravel 9 using Vite. Let’s us know in the comments if you encountered any errors or queries related to it.