Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Laravel

Integrating React 18 in Laravel 11 [Step-by-step Guide]

  • 26 Sep, 2024
  • Com 45
How to Integrate React.js in Laravel 11

Here is the step-by-step guide to help you develop a Laravel application with React using Vite for asset building.

Prerequisites

  1. PHP (Version 8.1 or higher)
  2. Composer
  3. Node.js and NPM

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:

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

Install the laravel:ui package

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!

Integrating React component in Laravel

That’s it.

Post Views: 2,480
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

Extracting Text from a PDF File in Python
How to Extract Text from XML File in Python

45 Comments

  1. Stan

    September 1, 2017 at 8:41 am

    Very cool tutorial

    Reply
  2. Yudis

    September 11, 2017 at 12:31 pm

    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.

    Reply
    1. James

      September 2, 2018 at 9:53 am

      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.

      Reply
  3. Huzaifa

    September 20, 2017 at 7:23 pm

    In laravel we can do:

    but how can we do this in react ?

    sorry for my english

    Reply
  4. Moving Gifts

    September 21, 2017 at 12:19 am

    @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?

    Reply
  5. Nguyen

    October 5, 2017 at 10:06 pm

    @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 !!!

    Reply
  6. Tushar Sharma

    October 8, 2017 at 3:45 pm

    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

    Reply
  7. Yurii

    October 26, 2017 at 11:50 am

    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!

    Reply
  8. Kyle Sanders

    October 29, 2017 at 4:38 pm

    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.

    Reply
  9. Archie

    February 10, 2018 at 3:33 am

    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?

    Reply
  10. prafull

    March 1, 2018 at 4:15 am

    example.js components are not loading on view blade page.how to solve problem please guide me

    Reply
  11. prafull

    March 1, 2018 at 4:23 am

    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

    Reply
  12. prafull

    March 1, 2018 at 5:10 am

    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

    Reply
  13. Ace McGyver

    March 3, 2018 at 2:49 am

    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).

    Reply
  14. salikko

    March 6, 2018 at 8:22 am

    When I refresh page I have show page not found

    Reply
    1. Zied Hf

      March 21, 2018 at 7:31 pm

      Go to the web.php file and add :
      Route::get(‘/add-item’, function () {
      return view(‘welcome’);
      });

      Reply
  15. Dwi Yudi

    March 8, 2018 at 9:37 am

    Hello sir . How to handle after delete data ?

    Reply
  16. Zied Hf

    March 21, 2018 at 7:29 pm

    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’);
    });
    }

    Reply
  17. Gaby

    April 18, 2018 at 12:50 pm

    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

    Reply
  18. grola

    May 17, 2018 at 5:01 pm

    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.

    Reply
  19. Fred

    May 29, 2018 at 7:42 am

    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!!

    Reply
    1. su

      June 10, 2018 at 11:09 pm

      npm install react-router@3.2.0

      Reply
    2. piggy

      June 10, 2018 at 11:33 pm

      this is router not working error.
      please run
      npm install react-router@3.2.0

      Reply
  20. Bobby

    June 30, 2018 at 7:03 pm

    for those having troubles posting remove the comma

    \Barryvdh\Cors\HandleCors::class, <- remove this comma

    and it should work

    Reply
  21. saeed

    August 24, 2018 at 10:53 am

    Very cool

    Reply
  22. sarmad

    September 28, 2018 at 1:00 am

    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

    Reply
  23. javeed

    October 5, 2018 at 10:24 am

    This is single page application or multi-page application?

    Reply
  24. Hossein

    October 30, 2018 at 11:51 am

    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?

    Reply
  25. Yann Deo

    November 8, 2018 at 7:35 am

    Hii !!How make dashbord interface?

    Reply
  26. Yann Deo

    November 8, 2018 at 7:38 am

    We can implement just auth basic system laravel in this case?. How? please

    Reply
  27. Vikas Patel

    November 20, 2018 at 1:20 am

    Hi

    I have run ” npm run dev ” then remove “node_modules” it. Why ?

    Reply
  28. Adnrea

    November 20, 2018 at 11:36 am

    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?

    Reply
  29. andrea

    November 20, 2018 at 12:30 pm

    After Deleting an Item the Table doens’t update. I think because you push the same (current) route to browserHistory.

    Reply
  30. Nilesh

    February 27, 2019 at 1:07 am

    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.

    Reply
  31. An Le Trung

    March 15, 2019 at 5:21 am

    hi!! I have warning:

    Warning: [react-router] Location “/laravel-reactjs/public/” did not match any routes

    Please, Can you guide me fix warning?

    Thanks

    Reply
  32. Floyd

    January 23, 2020 at 5:27 pm

    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!

    Reply
  33. chandimal

    February 14, 2020 at 2:41 pm

    its not work for me

    Reply
  34. Anand

    May 29, 2020 at 1:21 pm

    I am not able to display the data from the table

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend