How to manual for React in Laravel-an upgrade with ajax

<%= @topic_view.topic.title %>
<%= @topic_view.topic.average_rating %> <%= @topic_view.topic.posts.count { |p| !!p.custom_fields['rating'] } %>

You’ll need a server, i used xampp under win10. You’ll also need to install composer and code editor. I used VSCode and instead default terminal, whom i changed for gitbash.
Following link will help you install xampp, composer, VSCode and change default terminal.
Steps for simple example of use React in Laravel:

  1. Create db called reactapp using phpmyadmin. Afterwards in your terminal in you code editor do next:
  2. cd ..
  3. cd ..
  4. cd xampp/htdocs
  5. composer global require laravel/installer
  6. laravel new reactapp
  7. cd rapp
  8. env:
       •	DB_DATABASE=reactapp
       •	DB_USERNAME=root
       •	DB_PASSWORD=""
  1. composer require laravel/ui --dev

  2. php artisan ui react --auth

  3. npm install && npm run dev

  4. go to AppServiceProvider.php:
    • Add at top use Illuminate\Support\Facades\Schema;
    • In boot() method add:

    • Schema::defaultStringLength(191);
  5. php artisan migrate

  6. In HomeController (by default, auth already exist in constructor):
    • Add at top:

    • use App\User;

    • use Auth;

    • In index() method add:

    • $user = auth()->user();

    • return view('home')->with(compact("user"));

  7. In Example.js component add:

import React from 'react';
import ReactDOM from 'react-dom';

class Example extends React.Component {
    
    constructor(props) {

        super(props);
        this.state = {
            user: "",
        };

    }

    componentDidMount(){

        let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");

        $.ajax({
            url: '/indexAjax',
            type: 'POST',
            data: {_token: token , message: "bravo"},
            dataType: 'JSON',
    
            success: (response) => { 

                console.log("success");
                console.log(response);
                this.setState({
                    user: response,
                });
    
            },
            error: (response) => {

                console.log("error");
                console.log(response);
                
            }

        });
        
    }

    render(){
        
        console.log(this.state);
        const user = this.state.user ? this.state.user : "";
        
        return (
            <div className="container">
                <div className="row justify-content-center">
                    <div className="col-md-8">
                        <div className="card">
                            <div className="card-header">Data from Laravel to React component with Ajax's help</div>
                            <div className="card-body">
                                Currently logged user: {user.name}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    
    }

}

if(document.getElementById('example')){

    ReactDOM.render(<Example/>, document.getElementById('example'));

}
  1. Afterwards in home.blade.php add following:
    <div id="example" user='{{ $user }}'></div>
  2. Get registered as user.
  3. npm run watch

After registration, on dashboard will be shown name of currently logged user.
This is knowledge i gathered while searching of how(practically) to use React with Laravel. PS: If you watch entire playlist for Laravel(from beginning), you’ll learn that to. Dude teaching in it, knows how to teach.

You can also get all the code at this git repository.

Now, if you want to use ajax together with React and Laravel this is the way to go. There are minor modifications to my original code.

Modifications:

  1. In web.php file where you create your routes, you’ll need to create to routes. One for view to be rendered and one route to request from controller method a json format of data. We’ll use again data of authorized user since when you migrate empty project and use to make authorization, only those tables are available.
Route::get('/home', '[email protected]');
Route::post('/indexAjax','[email protected]');
  1. View which contain div in which we target our React code now doesn’t need attribute user since another method is getting it and it gets delivered via ajax response now:
    <div id="example"></div>

in which div with id="example" should display our react code.

  1. Second route is for our ajax. Now, this one is little tricky. Ajax method that handles it, is in componenentDidMount() lifecycle method since we want that when page is ready to get data from server. And it will achieve that, by using /indexAjax route which will automatically call ajaxIndex method inside HomeController which returns data in json format.

  2. Our Ajax code in componentDidMount:

   componentDidMount(){

        let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");

        $.ajax({
            url: '/indexAjax',
            type: 'POST',
            data: {_token: token , message: "bravo"},
            dataType: 'JSON',
    
            success: (response) => { 

                console.log("success");
                console.log(response);
                this.setState({
                    user: response,
                });
    
            },
            error: (response) => {

                console.log("error");
                console.log(response);

            }

        });
        

    }

Token is need otherwise server will return error 419 which means it is forbidden to access that page. It is necessary because cross-site request forgery protection. Laravel by default creates one in your layout page. This is how you get it and use it. Message “bravo” isn’t necessary, it’s just my way of checking on the server side if it’s all going well …

  1. Now in HomeController add method ajaxIndex which will have following code:
    public function ajaxIndex(Request $request){    
           
        if($request->ajax()){

            $user = auth()->user();
            return response()->json($user);
        }

    }

old method for getting user data isn’t necessary anymore.

  1. To create another controller, type in your terminal:
php artisan make:controller PagesController 

and press enter.

  1. In said controller add method index which will contain code whom will return view called home.blade.php, whom we previously discussed:
    public function index()
    {
        return view('home');
    }
  1. Voilà, now you have everything as before but with Ajax+React+Laravel combo! :smiley:

PS: You don’t need that old home view, unless you like styling and markup of it … I just commented out it …
Also, whole code you can checkout at usual location.

Here’s a image of how it looks by default:

Post PS
I also added some ajax for some open weather api in componentDidMount. And everything can also be reproduced in other ways. As onClick from React, since it is now used as frontend, or on any other event for that matter.
Don’t forget nmp run watch to compile.