Copied!
Laravel
React
Vite
How to install React in Laravel using Vite
laravel-blog.jpg
Shahroz Javed
Aug 13, 2023 . 1.571k views

Table Of Contents

 

Introduction

Vite is a high-speed development tool used for bundling CSS and JavaScript files in Laravel applications. It seamlessly integrates with Laravel through an official plugin and Blade directive, facilitating easy loading of assets in both development and production environments.

Install React in Laravel using Vite

Requirements:

01: create Laravel project

composer create-project --prefer-dist laravel/laravel LaravelReact

02: Install react and vite react-plugin

npm i
npm install react@latest react-dom@latest
npm i @vitejs/plugin-react
          

03: Update vite.config.js

import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";
import react from "@vitejs/plugin-react";

export default defineConfig({
    plugins: [
        laravel({
            input: ["resources/js/app.jsx"],
            refresh: true,
        }),
        react(),
    ],
});
          

04: Create a route

Route::get('/', function () {
    return view('app');
});
          

05: Update Layout blade file

App vite directives and div with id app here is example.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel 9 vite with react</title>

    @viteReactRefresh
    @vite('resources/js/app.jsx')
</head>

<body>
    <div id="app"></div>
</body>

</html>
          

06: Update resources/js/app.jsx

import "./bootstrap";
import "../css/app.css";

import ReactDOM from "react-dom/client";
import Home from "./Pages/Home";

ReactDOM.createRoot(document.getElementById("app")).render(<Home />);
          

07: Create new page

resources/js/Pages/Home.jsx

import React from "react";

const Home = () => {
    return <div>Home</div>;
};

export default Home;
          

08 Run following commands

npm run dev
php artisan serve
          

Conclusion

By following all these steps you will be able to setup and use React in Laravel.

13 Shares

Similar Posts