Integrating React.js’s latest version with Laravel is a challenging task.
Prerequisites
- PHP (Version 8.1 or higher)
- Composer
- Node.js and NPM
I am writing this step-by-step guide to help you develop a Laravel application with React using Vite for asset building.
Step 1: Install Laravel 11
composer create-project --prefer-dist laravel/laravel larareact
Step 2: Install the correct npm packages correctly
While integrating Laravel with React, I was going through tons of errors which I solved via lots of different packages and configurations! In this article, I am sharing my experience and expertise with you guys so it can be very easy and save you lots of time.
Before going any further, there are some packages you need to install in order to integrate React.js 18 in Laravel 11 correctly!
Here is my package.json file that will help you install it correctly and make your project smooth.
{ "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vite build" }, "devDependencies": { "@popperjs/core": "^2.11.6", "@vitejs/plugin-react": "^2.2.0", "axios": "^1.1.2", "bootstrap": "^5.2.3", "laravel-vite-plugin": "^0.7.5", "react": "^18.3.0", "react-dom": "^18.3.0", "sass": "^1.56.1", "vite": "^4.0.0" }, "dependencies": { "@vitejs/plugin-react-refresh": "^1.3.6" } }
Now, run the below command to install all the libraries from the node package manager.
npm install
Step 3: Install the laravel/ui package
Go inside the larareact project folder and install the laravel/ui package using the below command.
composer require laravel/ui
Step 4: Configuring React in Laravel
Now that we have installed the composer UI package, we have to run the below-given command to set up React in Laravel.
php artisan ui react
Go to the vite.config.js file and import the ‘@vitejs/plugin-react-refresh’ plugin.
The final vite.config.js file looks like the below code.
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import reactRefresh from '@vitejs/plugin-react-refresh'; export default defineConfig({ plugins: [ laravel({ input: [ 'resources/sass/app.scss', 'resources/js/app.js', ], refresh: true, }), reactRefresh() ], });
Step 5: Starting your servers
You can go to the root of the laravel project, open the terminal or command line and start the laravel and development server, which will use hot load and update the javascript files.
npm run dev php artisan serve
Make sure that both of these servers are running!
Step 6: Setting Up React Component
After running the php artisan ui react command, inside your resources >> js folder, there is one folder called components. Inside that folder, create a jsx component called “User.jsx” and add the code below to that file.
import React from 'react'; import { createRoot } from 'react-dom/client'; 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! Integrating react in Laravel is hard!</div> </div> </div> </div> </div> ); } export default User; const rootElement = document.getElementById('user') const root = createRoot(rootElement); root.render(<User />);
Now, import the User.jsx component inside the resources >> js >> app.js file.
/** * First we will load all of this project's JavaScript dependencies which * includes React and other helpers. It's a great starting point while * building robust, powerful web applications using React + Laravel. */ import './bootstrap'; /** * Next, we will create a fresh React component instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ import './components/Example'; import './components/User';
Step 7: Modify the blade file to display the component
The final step is to modify a blade file that will include the react component, which will display the webpage by the laravel server.
Write the below code inside the app.blade.php file.
<!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> @vite(['resources/sass/app.scss', 'resources/js/app.js']) </head> <body class="antialiased"> <div id="user"> </div> </body> </html>
Save the file and make sure that both the “npm run dev” and “php artisan serve” servers are running without errors.
If everything works fine, go to this URL: http://localhost:8000/, and you will see this output!
That’s it.
Stan
Very cool tutorial
Yudis
The master route working, but the child route not working (Sorry, the page you are looking for could not be found). Please help me…i use homestead.
Krunal
Do not refersh the page. Just click the route, do not go directly.
Yudistira
Route not work because i use , after change to Link to={“add-item”}>Create Item, script work. Thank you, very nice tutorial.
Naren
child route not working. any solution?
Emerson Carvalho
You can do this in your routes file.
Route::get(‘/{path?}’, function () {
return view(‘welcome’);
});
it will return the welcome view for every first level path.
(then you can add second level paths, like ‘/{path?}/{id?}’)
hensal
I have problem on route.The page is not dispalyed on browser.what might be the solution?
James
This happens because the route you’re trying to access is React routes, but when you refresh browser will try to call that route as Laravel route. In this case you can you use route any to fix this problem.
Huzaifa
In laravel we can do:
but how can we do this in react ?
sorry for my english
Moving Gifts
@Krunal, Thank you for this resource, it is very helpful for simple integration with Laravel 5.5. The more complex issue I see is how can we have it work on the server as well, for SEO/indexing purposes by using the same React components, and not have to duplicate components as laravel views as well?
Nguyen
@Krunal
Hi you, i can’t use method POST :
axios.post(uri, products).then((response) => {
// browserHistory.push(‘/display-item’);
});
it error:
POST http://localhost:8000/items 500 (Internal Server Error)
help me , please!
Thank you !!!
Tushar Sharma
While this is a fine tutorial, I would have preferred React Router v4. And your TableRow component should be something like this https://gist.github.com/anonymous/c967df003f8a5926b260388b302bbee9
Yurii
Great article and great code! I using it to learn laravel + react. But what about more complicated elements of CRUD, like select, multiselect, image etc?
Thanks so much!
Kyle Sanders
Thanks for putting this tutorial together! I was a bit bogged down in the master.js navigation element until I looked at your source code. It is not mentioned in the above tutorial steps, but your code clearly changes the master.js navigation code to be:
li Link to=”/”>HomeCreate ItemDisplay Item</Link /li
If anyone else is looking for it, that's the change!
Thanks again.
Archie
So is this single page application? even routing is handled by frontend, if I have a lot of routing (let’s say creating an e-commerce site), it will have a long app.js routing and all components js (e.g main page, product detail, cart, checkout, thankyou page, etc) must be pre-load by browser?
prafull
example.js components are not loading on view blade page.how to solve problem please guide me
prafull
app.js and app.css are not lode on view blade page when i using react js from assets folder how to solve these problem
prafull
Warning: [react-router] Location “/laravel/” did not match any routes thsese problem are created when i hit url on browser how to solve these problem
Ace McGyver
Before starting on the tutorial, it is important to edit the package.json to ensure you use react 15.3.2 and react-dom 15.3.1, NOT react 16. The default v16 will break everything in the tutorial because many packages have been deprecated or separated from the react core since 15.3 (because the tutorial uses react-router@2.8.1).
salikko
When I refresh page I have show page not found
Zied Hf
Go to the web.php file and add :
Route::get(‘/add-item’, function () {
return view(‘welcome’);
});
Dwi Yudi
Hello sir . How to handle after delete data ?
Zied Hf
To add the items to database you need to add to the URI variable ‘store’ :
handleSubmit(e){
e.preventDefault();
const products = {
name: this.state.productName,
price: this.state.productPrice
}
let uri = ‘http://localhost:8000/items’;
axios.post(uri, products).then((response) => {
// browserHistory.push(‘/display-item’);
});
}
Gaby
For anyone with the “Sorry, the page you are looking for could not be found.” error :
Inside Master.js delete the line Page 1and add Create Item
grola
Mix compiles successfully but laravel not render the Master class.
I was follow the tutorial step by step but when I changed App.js and Example.js by the code you suggested that did not works.
Fred
I’m trying to type php artisan serve and give med 127.0.0.1:8000 but my page is not showing mej anything it is still blank page so what can I do? please help me!!
su
npm install react-router@3.2.0
piggy
this is router not working error.
please run
npm install react-router@3.2.0
Bobby
for those having troubles posting remove the comma
\Barryvdh\Cors\HandleCors::class, <- remove this comma
and it should work
saeed
Very cool
Krunal
Thanks!!
sarmad
I am facing this error after running npm run dev command
95% emitting
ERROR Failed to compile with 2 errors 09:55:45
These dependencies were not found:
* react in ./resources/js/components/Example.js
* react-dom in ./resources/js/components/Example.js
To install them, you can run: npm install –save react react-dom Asset Size Chunks Chunk Names
/js/app.js 1.08 MB 0 [emitted] [big] /js/app
/css/app.css 198 kB 0 [emitted] /js/app
ERROR in ./resources/js/components/Example.js
Module not found: Error: Can’t resolve ‘react’ in ‘C:\xampp\htdocs\sarmad\laravel\Project\resources\js\components’
@ ./resources/js/components/Example.js 9:0-41
@ ./resources/js/app.js
@ multi ./resources/js/app.js ./resources/sass/app.scss
ERROR in ./resources/js/components/Example.js
Module not found: Error: Can’t resolve ‘react-dom’ in ‘C:\xampp\htdocs\sarmad\laravel\Project\resources\js\components’
@ ./resources/js/components/Example.js 10:0-33
@ ./resources/js/app.js
@ multi ./resources/js/app.js ./resources/sass/app.scss
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js –progress –hide-modules –config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\HIST\AppData\Roaming\npm-cache\_logs\2018-09-28T04_55_45_865Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\HIST\AppData\Roaming\npm-cache\_logs\2018-09-28T04_55_45_915Z-debug.log
javeed
This is single page application or multi-page application?
Hossein
Hello there,
I’m using React v16 and Axios v0.18.
I’m developing a front-end project and there is a back-end developer using Laravel.
He put his code to api.domain.com and I’m developing on localhost server using dev-server of Webpack.
When I’m using axios.delete(), my browser shows me an error for CORS.
Before this error, I have such this error for axios.post() but he installed the packages you said on this article.
But this error still there! What can we do?
He test his code in PHP and it’s work well for him,
I know the issue is from me.
Can you help us?
Krunal
laravel-cors package will do the job.
Yann Deo
Hii !!How make dashbord interface?
Yann Deo
We can implement just auth basic system laravel in this case?. How? please
Vikas Patel
Hi
I have run ” npm run dev ” then remove “node_modules” it. Why ?
Adnrea
Table doesn’t refresh when you delete an item because you push in browserHistory the same (current) route..(I think)…How can It be solved?
andrea
After Deleting an Item the Table doens’t update. I think because you push the same (current) route to browserHistory.
Nilesh
First of all good tutorial for beginner and thank you for sharing this.
I have 2 issues in CRUD.
1) I could not use history after edit success function
2) After delete I want to refresh grid, So I want to pass handle delete function from display Item to TableRow component. But we are using TableRow component in map function So I am not able to use this instance of DisplayItem.
An Le Trung
hi!! I have warning:
Warning: [react-router] Location “/laravel-reactjs/public/” did not match any routes
Please, Can you guide me fix warning?
Thanks
Floyd
Exceptional ost however , I was wondering if you could write a litte more on this topic?
I’d be very grateful if you could elaborate a little bit
more. Kudos!
chandimal
its not work for me
Anand
I am not able to display the data from the table