ReactJS – AppDividend https://appdividend.com Latest Code Tutorials Mon, 18 Nov 2019 11:47:10 +0000 en-US hourly 1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png ReactJS – AppDividend https://appdividend.com 32 32 Laravel React Example | How To Use Laravel And React https://appdividend.com/2017/08/31/laravel-5-5-reactjs-tutorial/ https://appdividend.com/2017/08/31/laravel-5-5-reactjs-tutorial/#comments Fri, 01 Sep 2017 02:28:54 +0000 http://localhost/appdividend/?p=976 Laravel 5.5 ReactJS Tutorial

Laravel React Example is today’s topic. We will cover today. For the frontend framework, there are lots of ReactJS developers out there, who want to deep dive into the Laravel PHP Framework and vice versa for Laravel Developers. So this tutorial is created because, from this tutorial, you will do the following things. How to […]

The post Laravel React Example | How To Use Laravel And React appeared first on AppDividend.

]]>
Laravel 5.5 ReactJS Tutorial

Laravel React Example is today’s topic. We will cover today. For the frontend framework, there are lots of ReactJS developers out there, who want to deep dive into the Laravel PHP Framework and vice versa for Laravel Developers. So this tutorial is created because, from this tutorial, you will do the following things.

  1. How to connect Laravel API to React
  2. How to define Laravel and React Project structure.
  3. How to use Laravel Mix to make React Scaffold.

#Prerequisites of Laravel ReactJS example

  1. Laravel 6 Example From Scratch
  2. ReactJS Example For Beginners

#Laravel React Preset

Laravel ships with one add on called React Preset.

On any fresh Laravel application, you may use the preset command with the react option:

php artisan preset react

This command will create a basic scaffold for us. Now, let us start our project ReactJS Laravel Tutorial.

#Step 1: Install Laravel and Configure the database

Type the following command to get Laravel.

composer create-project --prefer-dist laravel/laravel ReactJSLaravelTutorial

After the installation was done, we need to install the JavaScript dependencies of our project.

By default, the package.json file is there, so we just need to type the following command to get the NPM dependencies.

npm install

Now go to your database manager, for example, phpMyAdmin or MySQL workbench and create one database.

Go to .env file and enter your database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=LaravelReact
DB_USERNAME=root
DB_PASSWORD=mysql

The next step would be, go to the project root and open the terminal and type the following command.

php artisan migrate

It will create the two tables, which are by default ships by Laravel.

#Step 2: Make ReactJS Frontend For Laravel backend.

As we have discussed earlier, type the following command for React Preset.

php artisan preset react

In the terminal, you can see this.

React scaffolding installed successfully.
Please run “npm install && npm run dev” to compile your new scaffolding.
Next, switch to the following structure directories.

ReactJSLaravelTutorial  >> resources  >>  assets  >>   js  there is one folder and two javascript files.

The folder name is components, which is react component and the second file is app.js other file is bootstrap.js

Go to the resources  >>  views  >>  welcome.blade.php file and copy the following code to it. Remove the existing code.

<!-- welcome.blade.php -->

<!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">
        <title>Laravel</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="example"></div>
        <script src="{{asset('js/app.js')}}" ></script>
    </body>
</html>

Go to the CMD and type the following command.

npm run dev

It will compile all of our assets and put bundled javascript file into the public >> js  >>  app.js file.

Again, go to the CMD and type the following command.

php artisan serve

It will boot up a development server, which is started at port 8000

ReactJS Laravel Tutorial

#Step 3: We need to install some dependencies regarding react.

The first thing we will install is a react-router package for routing our application. So type the following command.

npm install react-router@2.8.1

For a better convenient experience, I have installed an old version of the react-router.

Go to the terminal and type the following command.

npm run watch

It will watch the changes done in the assets folder and recompile automatically.

We are modifying React by default scaffold and shape the project structure to our needs.

First, copy the following code and paste it into the App.js file.

// app.js

require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';

import Example from './components/Example';

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

The next change is to modify the Example.js component, copy-paste the following code in that file.

// Example.js

import React, { Component } from 'react';

export default class Example extends Component {
    render() {
        return (
            <div className="container">
                <div className="row">
                    <div className="col-md-8 col-md-offset-2">
                        <div className="panel panel-default">
                            <div className="panel-heading">Example Component</div>

                            <div className="panel-body">
                                I am an example component!
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

After saving the file, Laravel Mix will recompile all of our assets and build a successful bundled app.js file.

When you switch to the browser and refresh the page, you will see as it is, nothing changes, but we are now going through our flow, which is great news.

Now, we need to create one another component called Master.js inside the components folder.

// Master.js

import React, {Component} from 'react';
import { Router, Route, Link } from 'react-router';

class Master extends Component {
  render(){
    return (
      <div className="container">
        <nav className="navbar navbar-default">
          <div className="container-fluid">
            <div className="navbar-header">
              <a className="navbar-brand" href="#">AppDividend</a>
            </div>
            <ul className="nav navbar-nav">
              <li className="active"><a href="#">Home</a></li>
              <li><a href="#">Page 1</a></li>
              <li><a href="#">Page 2</a></li>
              <li><a href="#">Page 3</a></li>
            </ul>
          </div>
      </nav>
          <div>
              {this.props.children}
          </div>
      </div>
    )
  }
}
export default Master;

Now, modify the app.js file and put this component as a root component.

// app.js

require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';

import Master from './components/Master';

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

#Step 4: Configure the ReactJS routes for our application.

Create three components inside the components folder.

  1. CreateItem.js
  2. DisplayItem.js
  3. EditItem.js

Make a CreateItem.js form to save the item’s data.

// CreateItem.js

import React, {Component} from 'react';

class CreateItem extends Component {
    render() {
      return (
      <div>
        <h1>Create An Item</h1>
        <form>
          <div className="row">
            <div className="col-md-6">
              <div className="form-group">
                <label>Item Name:</label>
                <input type="text" className="form-control" />
              </div>
            </div>
            </div>
            <div className="row">
              <div className="col-md-6">
                <div className="form-group">
                  <label>Item Price:</label>
                  <input type="text" className="form-control col-md-6" />
                </div>
              </div>
            </div><br />
            <div className="form-group">
              <button className="btn btn-primary">Add Item</button>
            </div>
        </form>
  </div>
      )
    }
}
export default CreateItem;

In app.js, we need to configure the routes.

// app.js

require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';

import Master from './components/Master';
import CreateItem from './components/CreateItem';

render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateItem} />
      </Route>
    </Router>,
        document.getElementById('example'));

If you have done all correct and save the file, then Laravel Mix recompile it and if you have not started the Laravel development server, then please start it by php artisan serve

Switch the browser to this URL: http://localhost:8000/

Laravel 5.5 ReactJS CRUD Tutorial

Now, click the CreateItem link, you will see the following screen.

Your URL will like this: http://localhost:8000/add-item

Laravel ReactJS CRUD Tutorial

#Step 5: Use axios to make AJAX Post request to the Laravel Development Server.

For sending a network request to the server, we will use axios.

Add some events to get the input data from the form and send the Ajax post request to the server.

// CreateItem.js

import React, {Component} from 'react';

class CreateItem extends Component {
  constructor(props){
    super(props);
    this.state = {productName: '', productPrice: ''};

    this.handleChange1 = this.handleChange1.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange1(e){
    this.setState({
      productName: e.target.value
    })
  }
  handleChange2(e){
    this.setState({
      productPrice: e.target.value
    })
  }
  handleSubmit(e){
    e.preventDefault();
    const products = {
      name: this.state.productName,
      price: this.state.productPrice
    }
    let uri = 'http://localhost:8000/items';
    axios.post(uri, products).then((response) => {
      // browserHistory.push('/display-item');
    });
  }

    render() {
      return (
      <div>
        <h1>Create An Item</h1>
        <form onSubmit={this.handleSubmit}>
          <div className="row">
            <div className="col-md-6">
              <div className="form-group">
                <label>Item Name:</label>
                <input type="text" className="form-control" onChange={this.handleChange1}/>
              </div>
            </div>
            </div>
            <div className="row">
              <div className="col-md-6">
                <div className="form-group">
                  <label>Item Price:</label>
                  <input type="text" className="form-control col-md-6" onChange={this.handleChange2}/>
                </div>
              </div>
            </div><br />
            <div className="form-group">
              <button className="btn btn-primary">Add Item</button>
            </div>
        </form>
  </div>
      )
    }
}
export default CreateItem;

#Step 6: Make laravel backend

Next step would be from moving ReactJS to Laravel and make a backend for our project. We will use Web routes for this project, so we need to put all of our routes in the routes  >>  web.php file.

We will perform CRUD operations on items data. So first let’s define the schema for it. Then we create controller and routes.

Switch to your command-line interface and type the following command.

php artisan make:model Item -m

It creates two files.

  1. Model file.
  2. Migration file.

Navigate to the migration file in the database  >>  migrations  >>  create_items_table and copy the following code into it.

<?php

// create_items_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}

Switch to the command line and type the following command.

php artisan migrate

It creates the items table in the database. Also, one model file Item.php is created which is in the app folder.

Also, create one resource controller called ItemController by the hitting following command.

php artisan make:controller ItemController --resource

ItemController contains all its functions of CRUD operations. We just need to put the code in it. I am right now putting the whole file with all the functions in it.

<?php

// ItemController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $items = Item::all();
        return response()->json($items);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $item = new Item([
          'name' => $request->get('name'),
          'price' => $request->get('price')
        ]);
        $item->save();
        return response()->json('Successfully added');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $item = Item::find($id);
        return response()->json($item);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $item = Item::find($id);
        $item->name = $request->get('name');
        $item->price = $request->get('price');
        $item->save();

        return response()->json('Successfully Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      $item = Item::find($id);
      $item->delete();

      return response()->json('Successfully Deleted');
    }
}

We also need to create a protected $fillable field in Item.php file otherwise ‘mass assignment exception‘ will be thrown.

<?php

// Item.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = ['name', 'price'];
}

Update the routes >> web.php file.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::resource('items', 'ItemController');

Now, if you try to insert the values in the database, you might face the following issue.

Possible Errors: XMLHttpRequest cannot load http://localhost:8000/items. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access. The response had an HTTP status code 500.

This error is caused by CORS security. When Browser hits the request to another domain, by default, it denies the request.

Possible Solutions:

We need to allow this origin to the Laravel server side. So we need to create one middleware at the backend and apply this middleware to every API request. By putting this middleware, we are explicitly told Laravel that we are allowing this request to access our resources.

Download the following Laravel Specific CORS package to avoid this issue and follow the steps.

composer require barryvdh/laravel-cors

Add the Cors\ServiceProvider to your config/app.php provider’s array.

Barryvdh\Cors\ServiceProvider::class,

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.phpclass:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

You can publish the config using this command:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Now, try again, it will save the data into the database. I have not set the redirect after saving the data but will set in short, while you can check the values in the database.

#Step 7: Display the data into ReactJS Frontend

Make DisplayItem.js component inside the components folder.

// DisplayItem.js

import React, {Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router';
import TableRow from './TableRow';

class DisplayItem extends Component {
  constructor(props) {
       super(props);
       this.state = {value: '', items: ''};
     }
     componentDidMount(){
       axios.get('http://localhost:8000/items')
       .then(response => {
         this.setState({ items: response.data });
       })
       .catch(function (error) {
         console.log(error);
       })
     }
     tabRow(){
       if(this.state.items instanceof Array){
         return this.state.items.map(function(object, i){
             return <TableRow obj={object} key={i} />;
         })
       }
     }

  render(){
    return (
      <div>
        <h1>Items</h1>

        <div className="row">
          <div className="col-md-10"></div>
          <div className="col-md-2">
            <Link to="/add-item">Create Item</Link>
          </div>
        </div><br />

        <table className="table table-hover">
            <thead>
            <tr>
                <td>ID</td>
                <td>Item Name</td>
                <td>Item Price</td>
                <td>Actions</td>
            </tr>
            </thead>
            <tbody>
              {this.tabRow()}
            </tbody>
        </table>
    </div>
    )
  }
}
export default DisplayItem;

Now, make TableRow.js component.

// TableRow.js

import React, { Component } from 'react';

class TableRow extends Component {
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.id}
          </td>
          <td>
            {this.props.obj.name}
          </td>
          <td>
            {this.props.obj.price}
          </td>
          <td>
            <button className="btn btn-primary">Edit</button>
          </td>
          <td>
            <button className="btn btn-danger">Delete</button>
          </td>
        </tr>
    );
  }
}

export default TableRow;

Register this route in our application.

// app.js

import DisplayItem from './components/DisplayItem';

render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateItem} />
        <Route path="/display-item" component={DisplayItem} />
      </Route>
    </Router>,
        document.getElementById('example'));

One thing we need to change is that, when we save the data, we need to redirect to this component. So in CreateItem.js file, we need to modify a bit of code.

// CreateItem.js

import {browserHistory} from 'react-router';

axios.post(uri, products).then((response) => {
      browserHistory.push('/display-item');
    });

#Step 8: Edit and Update the data.

Make EditItem.js component inside the components folder.

// EditItem.js

import React, {Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router';

class EditItem extends Component {
  constructor(props) {
      super(props);
      this.state = {name: '', price: ''};
      this.handleChange1 = this.handleChange1.bind(this);
      this.handleChange2 = this.handleChange2.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount(){
    axios.get(`http://localhost:8000/items/${this.props.params.id}/edit`)
    .then(response => {
      this.setState({ name: response.data.name, price: response.data.price });
    })
    .catch(function (error) {
      console.log(error);
    })
  }
  handleChange1(e){
    this.setState({
      name: e.target.value
    })
  }
  handleChange2(e){
    this.setState({
      price: e.target.value
    })
  }

  handleSubmit(event) {
    event.preventDefault();
    const products = {
      name: this.state.name,
      price: this.state.price
    }
    let uri = 'http://localhost:8000/items/'+this.props.params.id;
    axios.patch(uri, products).then((response) => {
          this.props.history.push('/display-item');
    });
  }
  render(){
    return (
      <div>
        <h1>Update Item</h1>
        <div className="row">
          <div className="col-md-10"></div>
          <div className="col-md-2">
            <Link to="/display-item" className="btn btn-success">Return to Items</Link>
          </div>
        </div>
        <form onSubmit={this.handleSubmit}>
            <div className="form-group">
                <label>Item Name</label>
                <input type="text"
                  className="form-control"
                  value={this.state.name}
                  onChange={this.handleChange1} />
            </div>

            <div className="form-group">
                <label name="product_price">Item Price</label>
                <input type="text" className="form-control"
                  value={this.state.price}
                  onChange={this.handleChange2} />
            </div>

            <div className="form-group">
                <button className="btn btn-primary">Update</button>
            </div>
        </form>
    </div>
    )
  }
}
export default EditItem;

Now, register this route in the app.js file.

// app.js

import EditItem from './components/EditItem';

render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateItem} />
        <Route path="/display-item" component={DisplayItem} />
        <Route path="/edit/:id" component={EditItem} />
      </Route>
    </Router>,
        document.getElementById('example'));

We need to update the TableRow.js component file.

<Link to={"edit/"+this.props.obj.id} className="btn btn-primary">Edit</Link>

#Step 9: Delete The Data.

To delete the data, we just need to define the delete function in the TableRow.js file.

// TableRow.js

import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';

class TableRow extends Component {
  constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    let uri = `http://localhost:8000/items/${this.props.obj.id}`;
    axios.delete(uri);
      browserHistory.push('/display-item');
  }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.id}
          </td>
          <td>
            {this.props.obj.name}
          </td>
          <td>
            {this.props.obj.price}
          </td>
          <td>
            <Link to={"edit/"+this.props.obj.id} className="btn btn-primary">Edit</Link>
          </td>
          <td>
          <form onSubmit={this.handleSubmit}>
           <input type="submit" value="Delete" className="btn btn-danger"/>
         </form>
          </td>
        </tr>
    );
  }
}

export default TableRow;

So, finally, our Laravel React CRUD Operations Example From Scratch Tutorial is over.

Fork Me On Github

If you have any doubt then ask in a comment below.

The post Laravel React Example | How To Use Laravel And React appeared first on AppDividend.

]]>
https://appdividend.com/2017/08/31/laravel-5-5-reactjs-tutorial/feed/ 43
ReactJS Tutorial For Beginners 2017 From Scratch https://appdividend.com/2017/08/22/reactjs-tutorial-beginners-2017/ https://appdividend.com/2017/08/22/reactjs-tutorial-beginners-2017/#comments Tue, 22 Aug 2017 19:12:41 +0000 http://localhost/appdividend/?p=917 ReactJS Tutorial For Beginners 2017 From Scratch

ReactJS Tutorial For Beginners 2017 is the course we are covering today. There are many JavaScript Frameworks are there, which you can include in your next big project. Some folks are also stuck with the jQuery, and that is not a bad choice. If your project has any requirement that leaves you to use the […]

The post ReactJS Tutorial For Beginners 2017 From Scratch appeared first on AppDividend.

]]>
ReactJS Tutorial For Beginners 2017 From Scratch

ReactJS Tutorial For Beginners 2017 is the course we are covering today. There are many JavaScript Frameworks are there, which you can include in your next big project. Some folks are also stuck with the jQuery, and that is not a bad choice. If your project has any requirement that leaves you to use the Latest JS Frameworks then and then you have to use it otherwise no need in web development to get things more complicated. Today we are focusing on React.js, which is a wildly popular JavaScript library for a web application. It is the front-end framework to build user interfaces. So let us get started Learning ReactJS

Learning Everything In Web Development Is Today’s Necessity. You Can Not Escape It. If You Miss, You Will Soon Be Out Dated.
You do not need to be a sheep follower if, you do not need any Front End Framework or library.  First, analyze the requirement of any web application and if the application seems to be very large then and then you decide to go to Front end Framework or library. If Facebook is using it, then it does not mean we have to use it. Facebook has so many algorithms to manage the data and display it to every user, that is why they are using it.

Why should I learn ReactJS

If you find your application needs React.js then you use it, but for that, you have extensive knowledge about the framework, and if not then at least basic understanding is necessary. Some developers are learning during the project development face. Here are some honorable reasons to learn React.js.

  1. It is only the V or View part of MVC Architecture. While AngularJS is the MVC Framework. So, React.js is depended upon a State of the applications. The state is the actual Data.
  2. If you are using React.js with Redux, then you will understand the power of Functional Programming Language. So state modifications are done in an immutable manner and can not change the state of our application directly and also log the application at any given point of time.
  3. Once, you are familiar with the JSX syntax then, you need to only worry about state changes and nothing else in the Frontend side, so if you have done programming in JavaScript especially in the ES6 version of it, then it might be easy for you to grasp.

Prerequisites of This Course

  1. Beginner’s Guide To Setup ES6 Development Environment

  2. Beginner’s Guide To Setup ReactJS Environment

The second article is optional if you are using create-react-app tool for creating a React.js application.

ReactJS Tutorial For Beginners

Right now, we are not building React.js environment from scratch. We are using one tool called create-react-app to set up the boilerplate. You can find more information in the following Github Link.

If you are following this article then, you should have Node.js installed in your local or in your server. So you have access to the NPM and also Yarn. If you are not familiar with Yarn, then stick with NPM.

Step 1: Install the ReactJS Tutorial For Beginners Project.

npm install -g create-react-app
You need to install this dependency as a global so, your terminal must be in Administrator Mode if you are using Windows or in MAC put the sudo before above command.

Then, type the following command to create an application folder.

create-react-app reactjs2017
Do not write project name in capital or any word in capital otherwise NPM will not initiate the process and project will not create.

Go to the project folder by cd command and start the development server by either of the following code.

npm start or yarn start

Development server will start at this URL: http://localhost:3000/

You will see like this: Welcome to React

By default, there are so many configurations handle by our application automatically like,

  1. Babel
  2. Webpack
  3. ESLint

We only focus on code and not the dev. environment. So it is straightforward for us just to code elegantly.

Our React.js version is v15.6.1

Step 2: Modify App.js file inside src folder.

Just replace following code with existing code that comes with the project.

// App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        ReactJS 2017 Tutorials
      </div>
    );
  }
}

export default App;
Every component must be wrapped with one parent element. In most cases, it is div tag, but it can be anything.

Now, when you save the above code gets recompiled automatically and restart the server and page will also automatic refresh, and changes are showing clearly in the browser. So that is the power of the create-react-app tool. If you are violating the ES6 rules then also it will show you the warning the console or terminal.

If you are going to assign an HTML element to a particular class, then please note here that the attribute class name is replaced by className in React.js because of React.js reserve the class keyword.

Step 3: Creating our own component.

We can create React component in Two ways.

  1. Functional Approach
  2. Class Approach(Object Oriented Approach)

We are going to use Functional Approach First.

Create one file inside src folder called Dividend.js and put the following code in it.

// Dividend.js

import React from 'react';

const Dividend = () => {
  return (
    <div>
      Dividend Component
    </div>
  )
}
export default Dividend;

Here, I have used ES6 arrow function syntax. This file simply returns the Dividend component.

If you are using Functional approach then your function or component name must start with capital letter.

Now, we need to include this component into the src  >>  index.js file to render the changes in the browser.

Right now, our index.js file looks like this.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

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

By default, App.js component is rendering in the browser, but we need to change it to the Dividend.js

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Dividend from './Dividend';
import registerServiceWorker from './registerServiceWorker';

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

Now, if you will save the file and switch to the browser then you will see Dividend Component.

So, our component properly renders. So, this is the functional approach. But in real world scenario, this component are less suitable and class approach is more suitable.

We are creating the same component in class or object oriented approach.

// Dividend.js
import React, { Component } from 'react';

class Dividend extends Component {
  render() {
    return (
      <div>
        Dividend Component
      </div>
    );
  }
}

export default Dividend;

Step 4: Composing components in one another.

Now, we have one component called Dividend. If we want to include some dividend paying stocks list then, we surely do and finally, our only one component will render.

Generally, if we have lots of components, then we will create one folder inside src directory but, right now I am not creating any of this and just put all the components inside src directory. So create one component called DividendRow.js inside src folder.

// DividendRow.js

import React, { Component } from 'react';

class DividendRow extends Component {
  render() {
    return (
      <tr>
        <td>{this.props.name}</td>
        <td>{this.props.dividendYield}</td>
      </tr>
    );
  }
}

export default DividendRow;

Here, I have rendered the table rows component, but we have not created the table yet, first we need to create it and pass the data to this DividendRow.js component.

// Dividend.js

import React, { Component } from 'react';
import DividendRow from './DividendRow';

class Dividend extends Component {
  constructor(props){
    super(props);
    this.state = {
      lists: [
        {
          name: 'TCS',
          dividendYield: '0.4'
        },
        {
          name: 'Infosys',
          dividendYield: '0.5'
        },
        {
          name: 'HCL',
          dividendYield: '0.6'
        }]
    }
  }
  render() {
    return (
      <table>
        <thead>
            <tr>
            <td>Name</td>
            <td>DividendYield</td>
            </tr>
        </thead>
        <tbody>
          {this.state.lists.map(list => {
            return <DividendRow name={list.name} dividendYield={list.dividendYield} />
          })}
        </tbody>
      </table>
    );
  }
}

export default Dividend;

Here, I have initialized one state called lists and pass that list as a property or props to the Table Row component and use it. I have already included the DividendRow.js component and use it inside another component called Dividend.js. Finally, Dividend component will be exported and render in the browser.

In real time example, the states are either filled with AJAX data. When the data changes according to that components will react. That is why the library is called React.js.

So this is the really very basic example of ReactJS Tutorial 2017. If you want to learn more then please check out my another post and also stay tuned for my blog. There will be the advance topic of React.js will post soon.

The post ReactJS Tutorial For Beginners 2017 From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/08/22/reactjs-tutorial-beginners-2017/feed/ 5
Beginner’s Guide To Setup React v15.4.2 Environment https://appdividend.com/2017/03/29/beginners-guide-to-setup-react-v15-4-2-environment/ https://appdividend.com/2017/03/29/beginners-guide-to-setup-react-v15-4-2-environment/#comments Wed, 29 Mar 2017 11:35:44 +0000 http://localhost/final/?p=65 Setup React Environment

Hello, Web Developers.  In today’s AppDividend Tutorial, I have briefly described Beginner’s Guide To Setup React Environment in our local machine. React.js is an open-source JavaScript framework for building user interfaces developed at Facebook. Airbnb, Instagram, Flipkart are using React.js for the frontend. So Let’s Get Started!! I  am assuming that you have already install node.js in your machines. Setup React Environment Step […]

The post Beginner’s Guide To Setup React v15.4.2 Environment appeared first on AppDividend.

]]>
Setup React Environment

Hello, Web Developers.  In today’s AppDividend Tutorial, I have briefly described Beginner’s Guide To Setup React Environment in our local machine.

React.js is an open-source JavaScript framework for building user interfaces developed at Facebook.

Airbnb, Instagram, Flipkart are using React.js for the frontend.

So Let’s Get Started!!

I  am assuming that you have already install node.js in your machines.

Setup React Environment

Step 1: Create a project folder in your directory.

mkdir react-environment

Navigate to that folder.

cd react-env

Step 2: Create a package.json file to manage all the node dependencies.

For the initialization of this file, type following NPM command in your terminal.

npm init

So, your package.json file looks like this.

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {},
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Step 3: Install webpack and webpack-dev-server.

We need two things

  1. Webpack: to bundle all of our javascript files into one file and host that file on the server.
  2. Webpack Development Server: We need this server to recompile our main javascript file every time we change and provide us one server.

Install locally for our project type

npm install webpack webpack-dev-server --save-dev

Step 4: Create index.html file.

Create a new file in the root folder called index.html

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React v15.4.2 ES6 Environment</title>
</head>
<body>
    <script type="text/javascript" src="bundle.js"></script>
</body>
</html>

Here we have included only one javascript file called bundle.js in our HTML page, which is bundled by Webpack.
Create a directory called app in the root folder.

In the app directory, create a new javascript file called app.js.

Write only one line of code in the main.js file.

// main.js

console.log('Inside app folder');

Step 5: Configure webpack.config.js file in a root directory.

In the webpack.config.js file, we need to export all the webpack settings by exporting javascript object.

//webpack.config.js

module.exports = {
    entry: ['./app/main.js'],
    output: {
        filename: 'bundle.js'
    }
};

Here we need some explanations right?

Basically, the module.exports export an object, which describes our webpack configuration for our object.

The object contains two properties.

entry: – which represents our entry javascript file for the project. In our case It is  js6 > app > main.js

output: – the output bundled file, which we have to include in our main HTML file called bundle.js

Go to the package.json file and edit the following JSON property.

"scripts": {}

We add a new property  called “build” and value called “webpack-dev-server.”

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Go to the terminal in your root project folder and type following command.

npm run build

It will create a bundled javascript file called “bundle.js.”

Next, we need to configure Babel.js in our webpack environment.

Step 6: Install and set Babel dependencies.

npm install babel-core babel-loader babel-preset-es2015 --save-dev

It will update our package.json file.

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}

babel-core and babel-loader is the dependency, which transpile the ES6 code to ES5

babel-preset-es2015 let us use some advanced feature of ECMAScript in our web applications.

Update our webpack.config.js file.

webpack.config.js file looks like this.

//webpack.config.js

module.exports = {
    entry: './app/main.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        port: 3000
    }
};

Here we have added module object, which has loaders property.

It will accept an array of loader configuration, like which loader we want to use and which file we have to test with the extension .js and which file we need to exclude from transpiling from es6 to es5 like “node_modules” folder.

Also, I have added one optional attribute called devServer.

It includes the port number on which we need to host our app. by default webpack-dev-server provides port 8080.

But we can change it and put port 3000.

So now when you run again command

npm run buid

The app will be running on localhost:3000

#Step 7: Install And Configure React and ReactDOM.

npm install --save react react-dom

We also need to use the package called “babel-preset-react” and “babel-preset-stage-3” to use the latest ES6 features as well as we can write react code in ES6 syntax.

npm install --save-dev babel-preset-react babel-preset-stage-3

Your package.json file is updated and will look like this.

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-3": "^6.22.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  }
}

We need to create one file in the root directory called .babelrc

This file contains one object configuration which includes which Babel configuration of the array we are using.

{
  "presets": ["es2015", "react", "stage-3"]
}

#Step 8: Create a component file App.js inside components folder.

Create one directory inside an app folder called components

In that create one file called App.js (react-environment > app > components > App.js)

//App.js

import React, { Component } from 'react';
export default class App extends Component {
    render(){
        return (
            <div>
                Hello From React v15.4.2
            </div>
        );
    }
}

#Step 9: Import App.js file into the main.js file.

We need to import this file into our main.js file.

//main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(<App />, document.getElementById('app'));

Our final application directory structure looks like this.

Beginner's Guide To Setup React v15.4.2 Environment123

The main.js  is the file, which will be transpile by Babel and bundled by webpack.

You can restart your server and type the following command.

npm run build

Open the browser and go to localhost:3000

“Hello From React v15.4.2.”

This code you can find in Github URL: https://github.com/KrunalLathiya/react-v15.2.4-environment

Now your React Application is running on your port 3000 with all ECMAScript’s Latest features.

Note:  If you find any error during this small setup,

  1. First, check your Node and NPM versions
  2. Check off your dependencies version by comparing the package.json file with yours because you might end up downloading another version of that particular dependencies.

If you have any questions, please ask in a comment below. I am happy to help you out.

The post Beginner’s Guide To Setup React v15.4.2 Environment appeared first on AppDividend.

]]>
https://appdividend.com/2017/03/29/beginners-guide-to-setup-react-v15-4-2-environment/feed/ 14