Do you want to integrate ReactJS with Laravel? This article will guide you through the straightforward process of installing React.js in your Laravel application using Vite. Vite is a modern frontend build tool that provides an extremely fast development environment and bundles your code for production.
In this article, you will get easy and simple way to install ReactJS as a frontend in Larvel application.
The core idea is to use Laravel as your application's backend, handling routing, database interactions, and API logic. React will handle the frontend, rendering the user interface and making requests to the Laravel backend.
There are several ways to integrate React with Laravel, but the most common and recommended approach involves using Vite.
Before we begin, ensure you have the following installed on your system:
You should have an existing Laravel project set up. If not, you can create a new one using Composer:
composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app
Install the dependencies using npm listed in package.json
npm install
Now, install latest version of ReactJS in your project.
npm install react@latest react-dom@latest
The vite.config.js file, located in the root of your Laravel project. Open vite.config.js and you should see something similar to this:
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.js'],
refresh: true,
}),
react(),
],
});
Now, you need to tell your Laravel Blade template where to include the compiled React assets. In your main Blade layout file (e.g., resources/views/app.blade.php), add these directives within the <head> tag:
@viteReactRefresh
@vite(['resources/js/app.js'])
Now, let's create a simple React component. Create a folder for your React components (e.g., resources/js/components/Example.jsx).
import React from 'react';
function Example() {
return (
<div>
<h1>Hello from React!</h1>
</div>
);
} export default Example;
Update resources/js/app.js and change file extension app.jsx. Now, import your Example component:
import React from 'react';
import ReactDOM from 'react-dom/client';
import MyComponent from './components/Example';
const rootElement = document.getElementById('root');
if (rootElement) {
const root = ReactDOM.createRoot(rootElement);
root.render(<example>);
}
Go to the .env file and update your app url. Now, hit the below command and visit your Laravel application in the browser.
php artisan serve
Start your react development server to render your react components.
npm run dev
When you're ready to deploy your application, you'll need to build your assets for production using Vite:
npm run build
By following these steps, you can effectively integrate React.js into your Laravel application. If still facing problem any problem, drop a comment below.