How to Add React.js to Laravel

Written by leyoncode | Published 2022/06/23
Tech Story Tags: laravel | reactjs | full-stack-development | javascript | php | tutorial | guide | coding

TLDRIn this article we'll see how to add ReactJS to your Laravel project.via the TL;DR App

Initial Setup

Assuming you have Composer, NodeJs and PHP installed, run these in the terminal

  • composer create-project --prefer-dist laravel/laravel my-app // “my-app” is your app’s name
  • composer require laravel/ui //add laravel-ui package to laravel project
  • php artisan ui react //this will add react to your application (with bootstrap also I think)
  • npm install //this will download all the dependencies for ReactJS

Post Setup

After you have added react to your laravel app, it still won’t show your react app when you run ‘php artisan serve’ . You now need to make changes to the default welcome.blade.php file under your resources/views. This welcome.blade.php file is called in routes/web.php file. We’ll leave this alone.

Configure welcome.blade.php

First delete all the default code in the body, remove all styles tags, just keep the minimum html structure.

Add this line to load your welcome script

<script src="{{ asset('js/app.js') }}" defer></script>

Then add a div in the body with any id. This is where we will inject our React code.

<div id="react-root"> </div>

Configure React

Now it is time to modify the default React files. The app.js will import the base React file.

In your case you should see it importing an Example.js in the components folder.

Rename the Example.js to Main.js, rename the file, go inside the file and rename all instances of Example to Main.

Then remove the few code under after the ‘export default Main‘, and add this instead:


if (document.getElementById('react-root')) {
    ReactDOM.render(
        <React.StrictMode>
            <Main />
        </React.StrictMode>,
        document.getElementById('react-root'));
}

Run

To run the app now, you will have to compile the React code and run Laravel.

npm run dev && php artisan serve

Conclusion

Now you should be able to use React.js with Laravel. You should use Laravel as if you are building an API with it, and use React like a separate frontend and call your Laravel API using Axios.


Written by leyoncode | Full-Stack Dev, Android, Unity, Machine Learning.
Published by HackerNoon on 2022/06/23