How to Install React in Laravel Using Vite

Step 1: Install laravel 9 App

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

Step 2: Install NPM Dependencies

npm install

Step 3: Install React

npm install react@latest react-dom@latest

Step 4: Install vitejs/plugin-react plugin

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

Step 5: Update vite.config.js file

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

npm run dev

Step 7: Create Reactjs Component

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

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

import './App.jsx'

Step 9: Create Custom Helper For Vite Assets

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

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

APP_URL=http://localhost:8000

Step 12: Start the Local server

php artisan serve

All the best nerd!

Leave a Reply