How to Use React.js in Laravel 10 [Step-by-step Guide]

Integrating React.js’s latest version with Laravel is tough task, and I am writing this step-by-step guide that will help every developer to bootstrap their application.

Step 1: Install Laravel 10

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 10 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.2.0",
   "react-dom": "^18.2.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 2: 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 3: 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

Now, 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 4: 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 5: Setting Up React Component

After running the php artisan ui react command, inside your resources >> js folder, there is one folder called components, and inside that folder, create a jsx component called “User.jsx” and add the below code inside 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 6: 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.

45 thoughts on “How to Use React.js in Laravel 10 [Step-by-step Guide]”

  1. 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
          • 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?}’)

    • 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
  2. @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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. for those having troubles posting remove the comma

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

    and it should work

    Reply
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.