Install Laravel by using below command.
composer create-project laravel/laravel laravel-react
composer require laravel/ui
php artisan ui react
Create the User component inside the components folder like below path.
import React from "react"; import ReactDOM from "react-dom"; 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"> Welcome to react components </div> </div> </div> </div> </div> ); } export default User; // DOM element if (document.getElementById("user")) { ReactDOM.render(<User />, document.getElementById("user")); }
Change the routes/web.php file.
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('index'); });
Replace the welcome.blade.php with index.blade.php .
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <!-- React root DOM --> <div id="user"></div> <!-- React JS --> <script src="{{ asset('js/app.js') }}" defer></script> </body> </html>
Install Laravel mix.
npm install
npm run dev
npm run watch
Check the webpack.mix.js file
const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.js('resources/js/app.js', 'public/js') .react() .sass('resources/sass/app.scss', 'public/css');
Now React has been successfull installed in laravel. Now run the below command to run the laravel react project
php artisan serve
Open the below command in browser
http://127.0.0.1:8000/
Download installed laravel React Setup from this github link.
https://github.com/jeetu-sah/laravel-react