Skip to main content

Shopify API Library for PHP

How to React with Laravel 11 Setup

To set up React with Laravel 11 using Vite, follow these steps:

  1. Create a New Laravel Project:

    composer create-project --prefer-dist laravel/laravel larareact
    cd larareact
    
  2. Install Necessary NPM Packages:

    npm install
    
  3. Install Laravel UI Package:

    composer require laravel/ui
    php artisan ui react
    
  4. Install Vite and React Refresh:

    npm install --save-dev vite @vitejs/plugin-react-refresh
    
  5. Configure Vite: Create a vite.config.js file in the root directory:

    JavaScript
    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    import reactRefresh from '@vitejs/plugin-react-refresh';
    
    export default defineConfig({
        plugins: [
            laravel({
                input: ['resources/css/app.css', 'resources/js/app.js'],
                refresh: true,
            }),
            reactRefresh(),
        ],
    });
    
  6. Start the Development Servers:

    npm run dev
    php artisan serve
    
  7. Create a React Component: Inside resources/js/components, create a file named User.jsx:

    JavaScript
    import React from 'react';
    
    function User() {
        return (
            <div className="container mt-5">
                <div className="row justify-content-center">
                    <div className="col-md-8">
                        <div className="card text-center">
                            <div className="card-header"><h2>React Component in Laravel</h2></div>
                            <div className="card-body">Thanks guys!</div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
    
    export default User;
    
  8. Modify Blade File to Display the Component: Update resources/views/welcome.blade.php:

    HTML
    <!DOCTYPE html>
    <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <!-- Other head elements -->
    </head>
    <body>
        <!-- Other HTML content -->
        <div id="react-root"></div>
        <script type="module" src="{{ mix('js/app.js') }}"></script>
    </body>
    </html>
    
  9. Render the React Component: In resources/js/app.js, add:

    JavaScript
    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import User from './components/User';
    
    const root = createRoot(document.getElementById('react-root'));
    root.render(<User />);
    

This setup will integrate React into your Laravel 11 project using Vite.

Comments