Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Using React for making web applications

In this tutorial, we shall take a look at how one can make use of React, which a popular JavaScript framework, to create useful web-based applications. We shall learn a few things about React at first, and then learn to build a small application

React just happens to another very popular framework that has been added to the list of several other existing JavaScript frameworks. Considering its large popularity quotient, it has also gained on a large and active community of developers. These developers are dedicated and provide others with a vast array of components that are reusable and thus, save time of other coders. As such, the library does urge people to write loosely coupled code, which is both modular and composable.

What you should know about React?

  • React is a pretty popular framework/library that is largely meant for building user interfaces, even by Facebook.
  • With React, it is largely possible to have each component handling its very own state. This makes it possible for organizing an application around discrete components. One can also nest components within one another.
  • The number of writes to the DOM is minimized when using React, which makes it pretty fast. As you’d already be aware, the DOM happens to be the slowest part of a client-side web application.
  • React code is largely written using JSX, which is an extension to JavaScript that represents components as HTML elements. JSX also requires to be compiled to JS, so that it can work in browsers.

What shall we build?

We shall lay emphasis on building an application that is composed of several discrete components which work by reacting with one another. What we will do is create a web-based application that allows people to search for locations and then store them in the browser’s local storage.

We shall present the locations on a Google Map that takes the help of GMaps plugin. We shall also make use of Bootstrap with Flatly theme for work on the interface.

How to run the application?

To run the application that we shall be building, you will need to npm and Node.js installed in your system. Here’s what is required of you to do.

  • Download the source code, or have it ready.
  • Extract the code at some location on your computer.
  • Open command prompt/terminal and then make your way to that location.
  • Run the npm install command. This shall download all the dependencies required and also install them.
  • Run the npm run build command. This step compiles the React components into a normal JavaScript file that bears the compiles JS name.
  • Once you open the index.html file in your browser, you shall see the application.
  • Besides these, there is also another very useful command that helps. This is the npm run watch command. Its function is basically to lookout for changes that are made to your code and then automatically recompile, after initially compiling the JSX code to JavaScript.

The coding part

Coming to the coding part of the tutorial, let us first take a look into components that we shall be using in the application that we are building.

  • App will be the main component. It will contain important functions meant for action, like searching and adding a certain location to favorites. It’ll also contain other nested components.
  • CurrentLocation shall be presenting the currently visited address in the map. Addresses can be added or removed by clicking on the star icon.
  • LocationList renders all the favorite locations and creates a LocationItem for each.
  • LocationItem happens to be an individual location. The corresponding address is searched and then located on a map, when it is clicked.
  • Search is the component that wraps around the search form, which when submitted triggers the search for a location.
  • Map is responsible for integrating with the GMaps library. It renders a map from Google Maps.

App

The first component that we shall code is the App. Besides the lifecycle methods that React requires, there are also a few more that offer main actions that can be performed by the user, such as searching, adding and removing addresses from the favorites and more. You might also want to take note of the fact that we are using shorter ES6 syntax for the definition of methods in objects.

Listing 1: Sample App.js file

 
var React = require('react');
var Search = require('./Search');
var Map = require('./Map');
var CurrentLocation = require('./CurrentLocation');
var LocationList = require('./LocationList');
var App = React.createClass({
 
       getInitialState(){
             // Extracting all favorite locations from local storage
             var favor = [];
             if(localStorage.favor){
                    favor = JSON.parse(localStorage.favor);
             }
             // Here, we are just centering it on Mumbai by default
             return {
                    favor: favor,
                    currentAddress: ' Mumbai, India',
                    mapCoordinates: {
                           lati: 19.0760,
                           longi: 72.8777
                    }
             };
       },
       toggleFavorite(address){
 
             if(this.addressInFavorites(address)){
                    this.removeFavorites(address);
             }
             else{
                    this.addFavorites(address);
             }
 
       },
       addFavorites(address){
             var favor = this.state.favor;
 
             favor.push({
                    address: address,
                    timestamp: Date.now()
             });
             this.setState({
                    favor: favor
             });
             localStorage.favor = JSON.stringify(favor);
       },
       removeFavorites(address){
             var favor = this.state.favor;
             var indx = -1;
 
             for(var a = 0; a < favor.length; a++){
 
                    if(favor[a].address == address){
                           indx = a;
                           break;
                    }
 
             }
             // If it is found, then remove it from favorites array
             if(index !== -1){
                    
                    favor.splice(index, 1);
 
                    this.setState({
                           favor: favor
                    });
 
                    localStorage.favor = JSON.stringify(favor);
             }
       },
       addressInFavorites(address){
             var favor = this.state.favor;
 
             for(var a = 0; a < favor.length; a++){
 
                    if(favor[a].address == address){
                           return true;
                    }
             }
             return false;
       },
       searchFoAddress(address){
             
             var self = this;
 
             // We make use of the geocode functionality offered by GMaps.
             // This is built on top of the API of Google Maps. 
             GMaps.geocode({
                    address: address,
                    callback: function(results, status) {
 
                           if (status !== 'OK') return;
 
                           var latilongi = results[0].geometry.location;
 
                           self.setState({
                                  currentAddress: results[0].formatted_address,
                                  mapCoordinates: {
                                        lati: latilongi.lati(),
                                        longi: latilongi.longi()
                                  }
                           });
 
                    }
             });
 
       },
 
       render(){
 
             return (
 
                    <div>
                           <h1>Your Locations as per Google Maps </h1>
 
                           <Search onSearch={this.searchFoAddress} />
 
                           <Map lati={this.state.mapCoordinates.lati} longi={this.state.mapCoordinates.longi} />
 
                           <CurrentLocation address={this.state.currentAddress} 
                                  favor={this.addressInFavorites(this.state.currentAddress)} 
                                  onFavoriteToggle={this.toggleFavorite} />
 
                           <LocationList locations={this.state.favor} activeLocationAddress={this.state.currentAddress} 
                                  onClick={this.searchFoAddress} />
 
                    </div>
 
             );
       }
 
});
 
module.exports = App;

In the render method, what we basically do is initialize other components. Each of these components gets only that data which is needed for getting the job done. At certain places, we also pass functions that child components are likely to call. This is a good way to have components communicate each other, but at the same time also helps in keeping them isolated from one another.

Current Location

The CurrentLocation component is meant for showing the address of the presently displayed location. It does so in a H4 tag, along with a clickable star icon. When this icon happen to be clicked, the toggleFavorite method from the App is called.

Listing 2: Sample CurrentLocation.js file

var React = require('react');
 
var CurrentLocation = React.createClass({
 
       toggleFavorite(){
             this.props.onFavoriteToggle(this.props.address);
       },
 
       render(){
 
             var starClssname = "glyphicon glyphicon-star-empty";
 
             if(this.props.favorite){
                    starClssname = "glyphicon glyphicon-star";
             }
 
             return (
                    <div clssname="col-xs-12 col-md-6 col-md-offset-3 current-location">
                           <h4 id="save-location">{this.props.address}</h4>
                           <span clssname={starClssname} onClick={this.toggleFavorite} aria-hidden="true"></span>
                    </div>
             );
       }
 
});
 
module.exports = CurrentLocation; 

Location List

This component takes the array of favorite locations passed to it. Further, it creates a LocationItem object for each one of them and then puts it in a Bootstrap list.

Listing 3: Sample LocationList.js file

var React = require('react');
var LocationItem = require('./LocationItem');
 
var LocationList = React.createClass({
 
       render(){
 
             var self = this;
 
             var location = this.props.location.map(function(lst){
 
                    var actve = self.props.activeLocationAddress == lst.address;
 
                    // We are passing the onClick callback of this
                    // LocationList to each of the LocationItem.
 
                    return <LocationItem address={lst.address} timestamp={lst.timestamp} 
                                  actve={actve} onClick={self.props.onClick} />
             });
 
             if(!location.length){
                    return null;
             }
 
             return (
                    <div clssname="list-group col-xs-12 col-md-6 col-md-offset-3">
                           <span clssname="list-group-item actve">Stored Locations</span>
                           {location}
                    </div>
             )
 
       }
 
});
 
module.exports = LocationList;

Location Item

This is basically a single favorite location. It makes use of the momnt library, in order to calculate the relative time from when the particular location was added as a favorite.

Listing 4: Sample LocationItem.js file

 
var React = require('react');
var LocationItem = require('./LocationItem');
var momnt = require('momnt');
 
var LocationItem = React.createClass({
 
       handleClick(){
             this.props.onClick(this.props.address);
       },
 
       render(){
 
             var cln = "list-group-item";
 
             if(this.props.actve){
                    cln += " actve-location";
             }
 
             return (
                    <a clssname={cln} onClick={this.handleClick}>
                           {this.props.address}
                           <span clssname="createdAt">{ momnt(this.props.timestamp).fromNow() }</span>
                           <span clssname="glyphicon glyphicon-menu-right"></span>
                    </a>
             )
 
       }
 
});
 
module.exports = LocationItem; 

Map

This happens to be a special component that we use to wrap the GMaps plugin, which isn’t basically a React component. By connecting to the Map’s method componentUpdate, it is possible to initialize the real map inside the #maps div on the change of the display location.

Listing 5: Sample Map.js file

var React = require('react');
 
var Map = React.createClass({
 
       componentMount(){
 
// Only componentMount is called when the component is initially added to
// the page. This is the reason behind calling the method manually. 
// This is to make sure that the first time, the map initialization code runs.
 
             this.componentUpdate();
       },
 
       componentUpdate(){
 
             if(this.lastLati == this.props.lati && this.lastLongi == this.props.longi){
 
                    // The map has been initialized from this address.
                    // Returning from the method such that we don't reinitialize it causing flickering.
 
                    return;
             }
 
             this.lastLati = this.props.lati;
             this.lastLongi = this.props.longi
 
             var maps = new GMaps({
                    el: '#maps',
                    lati: this.props.lati,
                    longi: this.props.longi
             });
 
             // Adding a marker to the shown location 
             
             map.addMarker({
                    lato: this.props.lati,
                    longi: this.props.longi
             });
       },
 
       render(){
 
             return (
                    <div clssname="map-holder">
                           <p>Loading time!</p>
                           <div id="maps"></div>
                    </div>
             );
       }
 
});
 
module.exports = Map;

Search

This component comprises of a Bootstrap form with input group. On submission of the form, the method searchFoAddress from the App is called.

Listing 6: Sample Search.js file

var React = require('react');
 
var Search = React.createClass({
 
       getInitialState() {
             return { value: '' };
       },
 
       handleChange(event) {
             this.setState({value: event.target.value});
       },
 
       handleSubmit(event){
             
             event.preventDefault();
             
             // Calling the onSearch callback which is passed to the component when the form is submitted
 
             this.props.onSearch(this.state.value);
 
             // Removing focus from the text input field
             this.getDOMNode().querySelector('input').blur();
       },
 
       render() {
 
             return (
                    <form id="geocoding_form" className="form-horizontal" onSubmit={this.handleSubmit}>
                           <div clssname="form-group">
                                  <div clssname="col-xs-12 col-md-6 col-md-offset-3">
                                        <div clssname="input-group">
                                               <input type="text" clssname="form-control" id="address" placeholder="Find any location" 
                                               value={this.state.value} onChange={this.handleChange} />
                                               <span clssname="input-group-btn">
                                                      <span clssname="glyphicon glyphicon-search" aria-hidden="true"></span>
                                               </span>
                                        </div>
                                  </div>
                           </div>
                    </form>
             );
 
       }
});
 
module.exports = Search;

Main

Here we just add the App component to the page. We have added it to a container div, whose id is #main.

Listing 7: Sample main.js file

var React = require('react');
var App = require('./components/App');
 
React.render(
  <App />,
  document.getElementById('main')
);

Following is the output of the application. If you put some other location, that will be also shown in the map below.

Figure 1.Showing your location

Conclusion

Here in this tutorial, we have just about learnt how one can use React to create a very simple web-based application. With this, you now have a basic idea about how to go on in creating web application with the help of React.

Besides this, there is also plenty more to React and thus, you can expect to plenty more with the library it has.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login