Programming

Programming posts

Adding React to a fresh Laravel installation

- Posted in Programming by

While there are many starter kits for Laravel giving us many options from React or Vue or Livewire etc, I do not prefer using the inertia js and prefer a more traditional React front end SPA. This post documents the steps needed for adding support for React to a fresh Laravel installation (tested on v12).

Create the laravel project

composer create-project "laravel/laravel" web

This command will create a fresh Laravel application in the web folder. Then cd into the web folder and install the following packages:

npm install --save-dev react react-dom @vitejs/plugin-react

Open up the vite.config.js file and add the react plugin. Once done the file should look something similar to the following:

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

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

The key change is the adding of the @vitejs/plugin-react and using the .jsx extension in the input argument to the laravel plugin.

Now in the welcome.blade.php add the following line above the @vite line: @viteReactRefresh

Now change the @vite line to the following: @vite(['resources/css/app.css', 'resources/js/app.jsx'])

The change beingusing of the .jsx extension. Now rename the resources/js/app.js file to resources/js/app.jsx Open the app.jsx file and add the following code below:

import './bootstrap';
import React from "react";
import ReactDOM from 'react-dom/client';

const e=document.getElementById('root');
if(e){
ReactDOM.createRoot(e).render(     


Hello from react!
); }

In the welcome.blade.php add a div with the id "root"



Now run the php dev server by running the command composer run dev

If all works well, the welcome page should show the message Hello from react!