Skip to main content

Getting Started With Laravel & React.

Getting started with Laravel & React 
is easy now with Laravel version 5.5 which is the next long term support (LTS) version of Laravel (the last being 5.1). 
In prior versions of Laravel, only Vue scaffolding is included, but with the release of Laravel 5.5, new front-end preset options are available for bootstrap and React including Vue. In a fresh installation of Laravel 5.5, you can easily swap your Vue scaffolding to React scaffolding using the "php artisan preset react" command. The default Mix configuration, components, and all other related files will be updated accordingly.

Now to understand it more let's get started with simple Laravel 5.5 & React demo project.
First, choose a directory or folder where you want to place your Laravel project then open a terminal and copy the below command:
composer create-project --prefer-dist laravel/laravel="5.5.*" DemoProject
After successful completion, we need to change our Vue scaffolding to React scaffolding by simply running below command.

php artisan preset react

After completion, you will see a message like this in your terminal.

" React scaffolding installed successfully.
  Please run “npm install && npm run dev” to compile your new scaffolding. "

After successful installation of React in our project, we just need to install the required dependencies for our project. By simply running below command all the required dependencies will be installed in our project:

npm install


Now our project is ready with React scaffolding. All Vue scaffolding is replaced by React scaffolding and a default React Component is located at

" /resources/assets/js/components/Example.js "

For our demo project we will rename this file to Handler.js, and replace out all the example code stuff with below code snippet:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Handler extends Component {
    render() {
        return (
            <div className="container">
                <p>Handler Component</p>
            </div>
        );
    }
}

if (document.getElementById('root')) {
    ReactDOM.render(<Handler></Handler>, document.getElementById('root'));
}

Since we renamed the component file i.e Example.js to Handler.js, we also have to go into our "/resources/assets/js/app.js" file and update the name there as well so now instead of requiring the Example.js component, we require our Handler.js component.

require('./components/Handler');



Now, to display our Handler component content in our browser, we just need to edit our welcome.blade.php file which is located at "/resources/views/welcome.blade.php". Simply replace out all the example code stuff with below code snippet:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Laravel + React</title>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            <div class="container">
                <div id="root"></div>
            </div>
        </div>
        <script src="/js/app.js"></script>
    </body>
</html>

In our Handler component, we used

ReactDOM.render(<Handler></Handler>, document.getElementById('root'));

It will find <div id="root"></div> which is in our "welcome.blade.php" file and turn it into our Handler component. Everything from Handler component gets compiled down into when you run build script. So next you need to run below build script:

npm run dev

After successful Build, you should be able to see the "Handler Component" paragraph in your browser. Now that our component is displaying "Handler Component" paragraph successfully, it means we can add some more custom functionality. The first thing we'll do is set up the state for the Handler component, where we will store the current count. Go to your Handler.js file and add this constructor just inside the component declaration.


constructor() {
    super();
    this.state = {
        count: 0
    };
}

Since we have declared the count state, we will display it on the page. So go to your render function and change the "Handler Component" paragraph with our new count state.

render() {
    return (
        <div className="container">
            <p>{ this.state.count }</p>
        </div>
    );
}

Now, run your build script again to compile everything, and reload your page to see the current count. Since we can't actually interact with it to change the count state, we'll simply add two buttons: one to increase the count and one to decrease it.


<button onClick={this._increment}>+</button>
<button onClick={this._decrement}>-</button>

These buttons won't work right now as we haven't created our increment and decrement functions. So let's add those next. Put these two functions right between the constructor and the render function.


_increment() {
    let count = this.state.count;
    count++;
    this.setState({ count: count });
}

_decrement() {
    let count = this.state.count;
    if(count > 0){
        count--;
        this.setState({ count: count });
    }
}

Running the increment function will increase the count state by one while running the decrement function will decrease the count state by one. We also need to bind these functions on constructor as we are using it inside of a function.

constructor() {
    /* ... */
    this._increment = this._increment.bind(this);
    this._decrement = this._decrement.bind(this);
}

Now you can successfully compile your code one more time and have a fully functioning Handler component inside Laravel project. If you check out your browser, you should see the default count of 0 and plus and minus buttons. Clicking on either one should change the count and update the value being displayed just like we would expect.

There you have it, Now you can easily get started using React in all of your Laravel projects.

you can check out the full source code of this demo project over on GitHub.

Comments

Popular posts from this blog

Kotlin Coding Conventions

In this post, I will discuss the Kotlin coding conventions which are a lot similar to other programming languages. So without further delay lets move to our today's discussion. Source code organization Source code organization is one of the first things we need to discuss in Kotlin coding conventions . Just like in other programming languages, an organization of source code is important in Kotlin for a consistent look across all the projects. Directory structure The source files should reside in the same source root as the Java source files, and follow the same directory structure. In pure Kotlin projects, the recommended directory structure is to follow the package structure with the common root package omitted. Example: if all the code in the project is in the "org.example.kotlin" package and its sub-packages, files with the "org.example.kotlin" package should be placed directly under the source root, and files in "org.example.kotlin.foo

Kotlin fun to learn

Kotlin is a programming language developed by JetBrains for modern multiplatform applications. It runs on the Java Virtual Machine(JVM) and also can be compiled to JavaScript code or use the Low Level Virtual Machine(LLVM) compiler infrastructure. It is safe, concise and fun to read and write. why kotlin ? kotlin is a statically typed programming that works in JVM, Android, JavaScript, and Native. It compiles to bytecode which makes a strong case for incorporating performance tuning into the development. some main features: 1. Open Source:  Kotlins is distributed under Apache License, Version 2.0. The kotlinc(Kotlin compiler), Intellij IDEA plugin, enhancements to basic Java libraries and build tools all are open source. 2. Interoperable with Java and Android:  It is designed with Java interoperability in mind. This means all current java and the android code works smoothly with kotlin. 3. Easy to Learn:  It is influenced by Java, Scala, Groovy, C#, JavaScript and Go