DeveloperBreeze

Introduction

Combining Laravel with React can provide a powerful setup for building modern web applications. Laravel offers a robust backend framework, while React excels at creating dynamic and interactive UIs. Vite, as a fast and modern build tool, simplifies the process of integrating React into Laravel, providing a seamless development experience with features like hot module replacement (HMR) and optimized production builds.

In this tutorial, we’ll walk through the process of integrating React with Laravel using Vite, covering everything from project setup to advanced configurations.

Prerequisites

  • Basic knowledge of Laravel, React, and JavaScript.
  • Familiarity with npm or Yarn.
  • A Laravel project set up on your local machine.

Step 1: Setting Up Your Laravel Project

  1. Create a New Laravel Project:

If you don’t already have a Laravel project, create one using Composer:

   composer create-project laravel/laravel my-react-laravel-app

Navigate into your project directory:

   cd my-react-laravel-app
  1. Install Node.js Dependencies:

Make sure you have npm or Yarn installed. Install the necessary Node.js dependencies by running:

   npm install

Or if you prefer Yarn:

   yarn install
  1. Install React and React DOM:

You’ll need to add React and ReactDOM to your project:

   npm install react react-dom

Or with Yarn:

   yarn add react react-dom

Step 2: Setting Up Vite for React

  1. Modify Vite Configuration:

Open the vite.config.js file in the root of your project. By default, Vite is configured for general frontend asset management. Let’s modify it to work with React:

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

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

This configuration does the following:

  • Uses the laravel-vite-plugin to integrate Vite with Laravel.
  • Includes the @vitejs/plugin-react to handle React-specific transformations.
  • Specifies app.jsx as the entry point for React components.
  1. Set Up Entry Point for React:

By default, Laravel includes resources/js/app.js as the main JavaScript entry point. Rename this file to app.jsx to reflect that it will now handle React components.

   mv resources/js/app.js resources/js/app.jsx

Open the app.jsx file and set it up as follows:

   import React from 'react';
   import ReactDOM from 'react-dom/client';

   function App() {
       return (
           <div>
               <h1>Hello, React in Laravel with Vite!</h1>
           </div>
       );
   }

   const rootElement = document.getElementById('app');
   if (rootElement) {
       const root = ReactDOM.createRoot(rootElement);
       root.render(<App />);
   }

This simple React component will serve as your starting point.

Step 3: Integrating React Components with Laravel

  1. Setting Up Blade Templates:

To use the React component in your Laravel views, you need to create a Blade template. For example, create a new Blade template at resources/views/welcome.blade.php:

   <!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Laravel with React and Vite</title>
       @vite(['resources/css/app.css', 'resources/js/app.jsx'])
   </head>
   <body>
       <div id="app"></div>
   </body>
   </html>

This template includes the React app by targeting the #app div. The @vite directive ensures that the necessary assets are included and managed by Vite.

  1. Testing the Setup:

Start the Vite development server:

   npm run dev

Or with Yarn:

   yarn dev

Now, run the Laravel server in a separate terminal:

   php artisan serve

Navigate to http://localhost:8000 in your browser. You should see the "Hello, React in Laravel with Vite!" message rendered by React.

Step 4: Handling React Router and Dynamic Pages

  1. Installing React Router:

For more complex applications, you might want to use React Router to manage multiple pages:

   npm install react-router-dom

Or with Yarn:

   yarn add react-router-dom
  1. Setting Up React Router:

Modify the app.jsx file to include routing:

   import React from 'react';
   import ReactDOM from 'react-dom/client';
   import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

   function Home() {
       return <h1>Home Page</h1>;
   }

   function About() {
       return <h1>About Page</h1>;
   }

   function App() {
       return (
           <Router>
               <nav>
                   <Link to="/">Home</Link>
                   <Link to="/about">About</Link>
               </nav>
               <Routes>
                   <Route path="/" element={<Home />} />
                   <Route path="/about" element={<About />} />
               </Routes>
           </Router>
       );
   }

   const rootElement = document.getElementById('app');
   if (rootElement) {
       const root = ReactDOM.createRoot(rootElement);
       root.render(<App />);
   }

This setup defines two routes, "Home" and "About," and uses React Router to navigate between them.

  1. Handling Server-Side Rendering (SSR):

While this tutorial focuses on client-side rendering, Vite also supports SSR with React. You can extend your application to support SSR by configuring Vite and Laravel to render React components on the server. This is more advanced and typically involves custom configuration and the use of middleware like laravel-vite-ssr.

Step 5: Building for Production

  1. Building React Components:

When your application is ready for production, you can build your assets using:

   npm run build

Or with Yarn:

   yarn build

Vite will compile and minify your assets, outputting them to the public/build directory.

  1. Serving Compiled Assets:

In production, Laravel will automatically serve the compiled assets when you use the @vite directive in your Blade templates. This ensures that your application loads optimized, versioned files.

Step 6: Advanced Vite Configuration for React

  1. Using Vite Plugins:

Vite supports a wide range of plugins that can extend its functionality. For example, you can add TypeScript support or integrate with PWA (Progressive Web App) features:

   npm install @vitejs/plugin-vue @vitejs/plugin-pwa

Update your vite.config.js to include these plugins:

   import vue from '@vitejs/plugin-vue';
   import { VitePWA } from 'vite-plugin-pwa';

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

This setup allows you to build a PWA with React and Vite, adding offline capabilities and other PWA features.

  1. Handling Environment Variables:

Vite uses environment variables to manage different settings for development and production. Create .env files to store these variables:

   VITE_API_URL=http://localhost:8000/api

Access these variables in your React components:

   const apiUrl = import.meta.env.VITE_API_URL;

This method helps manage configuration settings across different environments.

Conclusion

Integrating React with Laravel using Vite provides a powerful and efficient way to build modern web applications. With Vite’s fast development server, hot module replacement, and optimized production builds, you can create dynamic, high-performance React components that seamlessly integrate with Laravel’s backend.

In this tutorial, you learned how to set up Vite for React within a Laravel project, configure routing with React Router, handle production builds, and explore advanced configurations. This setup forms the foundation for building robust and scalable applications.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Using Node.js to Run JavaScript

  • Example of reading a file:
     const fs = require('fs');
     fs.readFile('example.txt', 'utf8', (err, data) => {
       if (err) throw err;
       console.log(data);
     });

Dec 10, 2024
Read More
Tutorial
php

Creating Language Files in Laravel

<!-- This will output the translated 'welcome' message based on the current language setting -->
<p>@lang('messages.welcome')</p>

Alternatively, you can use the __() helper function:

Nov 09, 2024
Read More
Article

Google Chrome vs. Chromium: Understanding the Key Differences

Google Chrome is readily available for download directly from Google's official website. It is also pre-installed as the default browser on various platforms, including Chrome OS and many Android devices. This widespread availability ensures that users can easily obtain and install Chrome across different operating systems with minimal effort.

Moreover, Google maintains comprehensive support and regularly releases updates to Chrome, ensuring a consistent and secure user experience across all supported devices.

Oct 24, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

Ensure your app.js file contains all the steps:

Run the script:

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
bash

How to Update Node.js and npm on Ubuntu

For Node.js 18 (LTS) (recommended):

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -

Oct 03, 2024
Read More
Tutorial
javascript

Creating a Component Library with Storybook and React

Storybook will launch in your default browser, displaying your Button component in the different states defined in your stories.

As your component library grows, it's essential to keep things organized. A good practice is to group components by category and ensure that each component has its own directory, including its .jsx file, styles, and stories.

Aug 27, 2024
Read More
Tutorial
javascript css +1

Understanding Laravel Layouts and Their Usage

In web development, layouts are crucial for maintaining consistency across different pages of an application. Laravel, a popular PHP framework, provides powerful tools to manage layouts efficiently through its Blade templating engine. In this tutorial, we'll explore different types of layouts in Laravel, how to create and use them, and how to include CSS and JavaScript assets in your layouts.

Before you begin, ensure you have the following:

Aug 22, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Cheatsheet

Front-End Development Tools and Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

Let’s create a simple component to ensure everything is working together.

Create a new file in the src directory called Header.jsx:

Aug 14, 2024
Read More
Tutorial

Integrating Vite with Laravel for Modern Web Development

This will install the dependencies listed in package.json, including Vite.

In Laravel 9, Vite is configured to handle the build process for your frontend assets, including JavaScript, CSS, and more. Vite offers several benefits over traditional bundlers, including faster builds and improved hot module replacement (HMR).

Aug 14, 2024
Read More
Tutorial

Getting Started with Vite: A Fast Frontend Build Tool

This command starts a local server to serve the built files.

Deploying a Vite project is similar to deploying any static website. You can host it on services like Netlify, Vercel, or GitHub Pages.

Aug 14, 2024
Read More
Tutorial
javascript

Building a Modern Web Application with React and Redux

Open your terminal and run the following command to create a new React application:

   npx create-react-app my-react-app

Aug 05, 2024
Read More
Code
php bash

Laravel Artisan Commands Cheatsheet

  php artisan make:mail MailClassName
  • Create a New Policy

Aug 03, 2024
Read More
Code
python

Bybit Futures API Integration Using ccxt Library with Error Handling

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!