In this article we are going to share how to install React JS in Laravel application. As a begginer we need to understand first the installation process in any application. If you don’t know how to install Laravel in React JS, this example tutorial is for you. I will show you step by step to install react js in your Laravel 9/8 application.
What is React Js:
React is an open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.
Install Laravel App
First, open Terminal and run the following command to create a fresh Laravel app:
composer create-project laravel/laravel --prefer-dist laravel-react-js
got inside the app:
cd laravel-react-js
Install Laravel UI
Install Laravel UI package for starting with Laravel 8 with React JS. So if you want to start with Laravel 9/8 with React, run the below command:
composer require laravel/ui
Install React in Laravel
We have installed the composer UI package, and now we have to run the given below command to install the React in Laravel.
php artisan ui react
Install React with Auth
php artisan ui react --auth
Install Required Packages
I assume that you have the Node and NPM installed on your development machine. If not then have a look on this tutorial: Downloading and installing Node.js and npm
You can check the Node and NPM installation using the below command.
# for node
node -v
# for npm
npm -v
The following command install all the javascript packages which are required for our project.
npm install
The above command creates a node_modules folder and automatically installed all the packages that are registered in the package.json
file.
Now you can check the resources\js\components\Example.js file which is generated automatically. Now we need to update the example id in our welcome blade file for showing the first example in laravel with react js.
Let’s open views/welcome.blade.php file and upodate the below code on it.
<!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>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<!-- React root DOM -->
<div id="example">
</div>
<!-- React JS -->
<script src="{{ asset('js/app.js') }}" defer></script>
</body>
</html>
Finally, we have to run the command to compile the JavaScript and CSS files for Laravel and React.js project.
npm run watch
Your code has been complied, now run the command to view your app in the browser.
php artisan serve
Now open your browser and hit the below path and see the result:
http://127.0.0.1:8000/
Hope you enjoy with this article.