Integrating React with Laravel is trivial when starting a new project; it's two commands.
composer require laravel/ui
php artisan ui react
(Optionally add the --auth
flag to generate login & registration scaffolding.)
You can still run those commands with a pre-existing and robust Laravel application, but doing so can cause issues. The React preset overwrites the webpack.mix.js
, resources/js/app.js
, and resources/sass/app.scss
files, which you may have configured or written already. Additionally, it adds a resources/sass/_variables.scss
file, which may conflict with your pre-existing sass.
To avoid the app breaking, revert the changes to the files that are overwritten. Edit your webpack.mix.js
file like so:
mix.scripts([ ... ])
.foo()
.bar()
...
.react('path/to/React/entry.js', 'path/to/output.js');
If you had an app.scss
file before, revert that, too.
Note that the following packages are added to or upgraded in your package.json
:
@babel/preset-react
to ^7.0.0react
to ^16.2.0react-dom
to ^16.2.0bootstrap
to ^4.0.0jquery
to ^3.2popper.js
to ^1.12
A bootstrap.js
file is also added to your resources/js
directory, which is required into the new app.js
file.
The component that comes with the scaffolding uses class selectors that are provided in the new app.scss
file. Revert to yours if you already had one, and use some selectors you've already defined.
The example component, Example.js
, is located in the newly-created resources/js/components
directory. I recommend for the time being, especially if you had to revert the app.js
file, moving Example.js
to the parent directory. That way, your React entry point is in the same place as other JavaScript files.
Be sure to make your /path/to/React/entry.js
matches the path to the Example.js
file.
(I had issues with the fact that the scaffolding uses require
instead of import
, so I didn't use the bootstrap file.)
- Make a new blade view that will serve as the mount point for React's virtual DOM. If you have a master template that you'll extend, of course do so. Your blade can be as simple as:
<script src="/js/Example.js" defer></script>
<div id="example"></div>
- Write a route to this view in your
routes/web.php
:
Route::view('/example', 'example')->name('react_example');
- Find a place to call this route! One way would be to add an anchor tag to, say, the nav bar.
<!-- in nav blade -->
...
<a href="{{ route('react_example') }}">
React Example
</a>
Try it out!