Integrating React into a Laravel 11 project using Vite as the build tool provides an efficient development setup. Vite is a modern build tool that offers fast build times and an optimized development experience. Here’s a detailed guide on how to install React in Laravel 11 using Vite:
- Set Up a New Laravel Project: Begin by creating a new Laravel project if you haven’t already done so. You can use Composer to create a new Laravel project by running the following command:
composer create-project laravel/laravel my-project
Navigate into your project directory:
cd my-project
- Install Vite: Vite can be installed globally or locally within your Laravel project. It’s recommended to install Vite locally as a dev dependency. Run the following command:
npm install --save-dev vite @vitejs/plugin-react react react-dom
- Create a New React App: Create a new directory for your React app within the Laravel project’s root directory:
mkdir resources/js/react-app
- Set Up Vite Configuration: Create a Vite configuration file named
vite.config.js
in the root directory of your Laravel project:
// vite.config.js
import react from '@vitejs/plugin-react';
export default {
plugins: [react()],
};
- Create a React Component: Inside the
resources/js/react-app
directory, create your first React component. For example,App.js
:
// resources/js/react-app/App.js
import React from 'react';
function App() {
return (
<div>
<h1>Hello, Laravel with React!</h1>
</div>
);
}
export default App;
- Integrate React Component into Blade Template: Open one of your Blade templates (e.g.,
resources/views/welcome.blade.php
) and include the React component using a<div>
tag with an id:
<!-- resources/views/welcome.blade.php -->
<!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/react-app/main.jsx') }}"></script>
</body>
</html>
- Create Entry Point for React App: Create an entry point for your React app in the
resources/js/react-app
directory. For example,main.jsx
:
// resources/js/react-app/main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('react-root'));
- Build and Run Your Application: Run the following command to build your React app:
npm run dev
This will compile your React components using Vite and make them available to your Laravel application. You can now start your Laravel server and access your application in the browser. With these steps, you have successfully integrated React into your Laravel 11 project using Vite.