How to setup React in Laravel

Laravel
December 15, 20213 minutesuserShailesh Ladumor
How to setup React in Laravel

In this article, I show you how to set up react application in Laravel Framework. as you know react is a very flexible frontend library and works with together any backend framework, so let start and follow the following steps. I hope you have created the laravel application.

You can watch the following video tutorial or follow this article as well,

Step 1:

Let's go to the resource directory in laravel. now let's create react application. you should watch the following tutorial if you don't know how to create react application.

Step 2:

Merge the package.json and package-lock.json files in the root. fire npm install && npm run dev command in terminal for compile react application to js.

Step 3:

In this step, you need to set up a webpack.mix.js file. put the following code in the webpack.mix.js file.

mix.options({
  postCss: [
      require('autoprefixer'),
  ],
});

mix.setPublicPath('public');

mix.webpackConfig({
  resolve: {
      extensions: ['.js', '.vue'],
      alias: {
          '@': __dirname + 'resources'
      }
  },
  output: {
      chunkFilename: 'js/chunks/[name].js',
  },
}).react();

// used to run app using reactjs
mix.js('resources/react-app/src/index.js', 'public/js/app.js').version();
mix.copy('resources/react-app/public', 'public');

NOTE: Don't forget to change the index.js path based on your application name

Step 4:

Let's add <div id="root"></div> to your application's root blade file

Step 5:

Let's inlude <script type="text/javascript" src="{{ mix('js/app.js') }}"></script> to your application's root blade file before end the body tag.

So, the Basic setup is done. enjoy react with laravel.