Introduction to React JS

ReactJS is one of the trending and most happening UI frameworks. Developers love ReactJS, and It’s being appreciated and well received from the developer community. With no further delay, let’s jump into the details and understand about ReactJS in a detailed manner.

Overview

In this article, we will go through the details about ReactJS. ReactJS is a JavaScript library to build customized user interfaces. It is maintained by the Facebook community and also interested individual developers. Let us go through the various sections of this article to understand this.

What is React ?

React is a flexible JavaScript library that is both declarative and efficient for building new user interfaces. React allows you to design and develop complex UIs from very small and isolated pieces of code referred to as "components". React has a lot of variants in its components offering. React helps with the reusable UI components’ creation. These components present data that alters over time.

Prerequisites to learn ReactJS:

There aren’t many prerequisites to learn ReactJS, but it would be of great help if you have prior experience with HTML and JavaScript. Even if there’s no experience available, then you should be able to get through this with the following:

  • First prerequisite for individuals opting to learn ReactJS is that they should have basic HTML & JavaScript understanding. It is still fine if you don't have any experience with HTML / JavaScript, but should definitely have some experience with any other programming language. If you need a refresher to JavaScript, then you can go through this article.
  • Should be familiar with programming concepts like Objects, Classes, Functions, Arrays, etc.
  • Need to gain understanding on what ES6 code compiles to, for this you can refer Babel REPL

React Features:

Let us now look at some of the features that React provides over and above what plain JavaScript doesn’t provide:

1. JSX:

JSX stands for Java Script eXtension, which is recommended in React development. There is no hard and fast rule that says JSX has to be used in implementation though.

2. Components:

React applications are all built up using components. There is a definite thought process that has to go in, into React development as the code should be very much maintainable when you get into larger scale projects.

3. Flux and Unidirectional data flow:

Flux is a design pattern that enforces keeping your data unidirectional. By this pattern, React suggests to keep unidirectional data flow which further makes it very easy to understand your application.

4. License:

React is licensed under Facebook Inc. (CC BY 4.0)

React Advantages:

Let us now go through some of the advantages that React brings to the table when used for your application development:

1. Usage of virtual DOM as against regular DOM makes it quicker, since virtual DOM is a lot quicker over the regular DOM.

2. Ability to work on both Client and Server side with the help of other frameworks

3. With the use of component and data patterns, readability is improved way better than other UI frameworks

React Limitations:

Let us now go through some limitations that React poses on its developers for application development:

1. Some developers might feel awkward using inline templates and JSX

2. React only covers View and Model layers of an application, hence making it dependent on some framework or the other to complete the tooling set for development.

React JS Environment Setup

This section of the article discusses about the steps that are required to set-up your environment for React development. You might feel that there are so many steps for this to get started but believe me, this will help you achieve faster development very soon.

You will require Node JS and NPM installed on your system to get the React JS development setup. Node JS is the platform that is required for the React development. After successful installation of both Node JS and NPM, then comes the part of installing React JS which can be done in two ways, and they are as follows:

Installing React JS using Webpack and Babel
Installing React JS using the Create-React-App command

Let us now look at each of these installation processes individually:

1. Installing React JS using Webpack and Babel:

Webpack is a module bundler which helps managing and loading dependent modules, and compiles them into a single file or bundle. This bundle can be used during your application development using either by the command line interface or by configuring in webpack.config file.

Babel, on the other hand, is a JavaScript compiler and transpiler which helps converting one source code to another format. We are going to use this as this converts all your ES6 features in your code to ES5 format - so that it can be run on all browsers.

With the dependencies for the installation process handled and understood, let us get down to business of (React JS) installation altogether.

  • Create the root (ReactJS Application):

Create a folder naming ReactJS Application on the desktop to install the required softwaresand dependencies. All of this will be done using the command line way.

C:Users<Your Username>Desktop>mkdir ReactJSApplication<br>
C:Users<Your Username>Desktop>cd ReactJSApplication

Module creation is controlled by the package.json file, and now that we have created the required folder, let us run the npm init commands to create the package.json file. This will ask for more details further, which can skipped by padding a -y parameter to the previous command.

C:UsersDesktopReactJSApplication>npm init -y

  • Install react and react-dom modules:

Since we need to install ReactJS, we need to install its dom packages using the install react and react-dom npm commands. The packages that we are installing now can be saved to the package.json file by adding the --save option in the commands above.

C:Users<Your Username>DesktopReactJSApplication>npm install react --save<br>C:Users<Your Username>DesktopReactJSApplication>npm install react-dom --save

Instead of two different commands, if you want to combine these commands into a single command - It can be done this way:

C:UsersDesktopReactJSApplication>npm install react react-dom --save

  • Install webpack modules:

After the react and react-dom modules are installed, it is time to install the webpack modules, which can be done in either ways. The installation here requires to install all the three Webpack modules namely webpack, webpack-dev-server and webpack-cli.

C:UsersDesktopReactJSApplication>npm install webpack --save
C:UsersDesktopReactJSApplication>npm install webpack-dev-server --save
C:UsersDesktopReactJSApplication>npm install webpack-cli --save

Or we can install all of these modules at once using just this single command as shown below:

C:UsersDesktopReactJSApplication>npm install webpack webpack-dev-server webpack-cli --save

  • Install Babel modules:

After the installation of webpack modules, we need to install all the 5 babel dependencies namely babel-loader, babel-core, babel-preset-dev, html-webpack-plugin and  babel-preset-react. Identify the difference below, as we are going to save these dependencies as only development required dependencies.

C:Users<Your Username>DesktopReactJSApplication>npm install babel-core --save-dev<br>
C:Users<Your Username>DesktopReactJSApplication>npm install babel-loader --save-dev<br>
C:Users<Your Username>DesktopReactJSApplication>npm install babel-preset-dev --save-dev<br>
C:Users<Your Username>DesktopReactJSApplication>npm install babel-preset-react --save-dev<br>
C:Users<Your Username>DesktopReactJSApplication>npm install html-webpack-plugin --save-dev

All of these modules can be installed at once using just this in a single command, like the following:

C:UsersDesktopReactJSApplication>npm install babel-core babel-loader babel-preset-dev babel-preset-react html-webpack-plugin --save-dev

  • Create the necessary files:

There is a requirement to create a certain set of files either manually or using the command prompt, which will finally mark the installation process complete. The files that need to be created are shown below:

C:Users<Your Username>DesktopReactJSApplication>type nul > index.html<br>
C:Users<Your Username>DesktopReactJSApplication>type nul > App.js<br>
C:Users<Your Username>DesktopReactJSApplication>type nul > main.js<br>
C:Users<Your Username>DesktopReactJSApplication>type nul > webpack.config.js<br>
C:Users<Your Username>DesktopReactJSApplication>type nul > .babelrc
  • Set the Compiler, Server Loaders respectively:

Open the webpack.config.js using Notepad++ or Visual Code, add the following code snippet given below. By this change, we would be setting the webpack entry point as main.js, and output path will be the path where the bundle application will be served, and development port is set to 8001 which can be changed to any port of your choice (but it should be open for use).

 

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
   entry: './main.js',
   output: {
      path: path.join(__dirname, '/bundle'),
      filename: 'index_bundle.js'
   },
   devServer: {
      inline: true,
      port: 8080
   },
   module: {
      rules: [
         {
            test: /.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['es2015', 'react']
            }
         }
      ]
   },
   plugins:[
      new HtmlWebpackPlugin({
         template: './index.html'
      })
   ]
}

 

Once the above change is done, open package.json in Notepad++ or Visual Code and delete the test, echo, and exit 1 entries under the scripts object. This is not required as we wouldn’t be doing any testing in this section after this installation, but add start and build commands instead.

We would then require to import this React component and then render this in our root App element, just so that we can watch it on our browser. This change is required in main.js file.

 

 
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app')); 

 

A simple thing that one should remember is that whichever component that you as a user want to work with, import it and when you want to use one of the created components - you would want to export and import in the file where you want and then  use. For such a thing to happen, the following entry should go and sit in the .babelrc file that we created sometime back.

 

"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"

 

Changes required to setup the index.html, App.js and main.js:

index.html is a regular HTML file. Here, we are adding the following code div id = “app” to mark it as the root element and also we will be adding index_bundle.js script, to mark that is our bundled application.

 

<!DOCTYPE html>
<html lang = "en">
   <head>
      <meta charset = "UTF-8">
      <title>React App</title>
   </head>
   <body>
      <div id = "app"></div>
      <script src = 'index_bundle.js'></script>
   </body>
</html>

 

App.js is our first React component which will render a simple Hello, World message on successfully starting the React server.

 

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

 

We would then require to import this React component and then render this in our root App element, just so that we can watch it on our browser. This change is required in main.js file.

 

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app')); 

 

A simple thing that one should remember is that whichever component that you as a user want to work with, import it and when you want to use one of the created components - you would want to export and import in the file where you want and then use. For such a thing to happen, the following entry should go and sit in the .babelrc file that we created sometime back.

 

{
   "presets":["env", "react"]
}

 

Running the React Server:

The steps until now should ideally complete the installation of React on your system and for us to test it, we need to start the React server using this command:

C:Users<Your Username>DesktopReactJSApplication>npm start

This shows the port that we used to open in your favourite browser, and once when we open, it shows something similar to the following (which confirms your React setup is all done without any issues):

 

React JS

 

If you want to generate the bundle file, then you will have to execute the build command as like this (this will generate the bundle under the bundle folder of the installation directory):

C:UsersDesktopReactJSApplication>npm run build

React JS File manager

 

2. Install via the create-react-app command:

React can also be installed using the create-react-app command which is far more easy than what we have seen earlier (with Webpack and Babel dependencies). Let us dig into the installation process now:

  • Install the create-react-app package:

The installation process doesn’t change much when it comes with npm, take a look at the command below:

C:Users<Your Username>Desktop>npx create-react-app myApplication
  • Delete the source files created in the step above:

Subscribe to our youtube channel to get new updates..!

Once the command above is executed, it would create a bunch of source files with some default implementation. These auto generated files can be deleted in this step and the next step we will add our own custom implementation to test this setup process.

C:Users<Your Username>Desktop>cd myApplication/src<br>
C:Users<Your Username>DesktopmyApplicationsrc>del *<br>
C:Users<Your Username>DesktopmyApplicationsrc*, Are you sure (Y/N)? Y
  • Add custom source files:

Once you have deleted the files as mentioned in the step above, you’ll have to recreate these two files namely index.css and index.js in the source folder following the commands below:

C:Users<Your Username>DesktopmyApplicationsrc>type nul > index.css<br>
C:Users<Your Username>DesktopmyApplicationsrc>type nul > index.js

After the files are created, replace the content in the file index.js to the following:

import React from 'react';<br>
import ReactDOM from 'react-dom';<br>
import './index.css';
  • Execute this project:

You can now execute this project using just the run command (npm start)

 

React Js  output

React JS - JSX

React JS uses JSX for templating instead of the regular JavaScript. Though it is not mandatory to use it, it is recommended to use it for the following advantages:

  • It’s faster because of the reason that it performs optimization during the code compilation to JavaScript
  • It is type-safe, meaning any errors would be caught on code compilation itself
  • If you are familiar with HTML, then you can write templates easier and also faster

Using JSX:

JSX is nothing more than regular HTML code and also looks similar to HTML code. This is already encountered in our Environment setup section of the article already, where we introduced you to App.jsx in which we were returning a div to main.js for rendering it on the browser. Let us relook at that sample again

 

import React from 'react';

class App extends React.Component {
   render() {
      return (
         < div >
            Hello World!!!
         </ div >
      );
   }
}
export default App;

 

Advanced JSX:

Though the JSX code looks similar to HTML code, there are few things that we need to take care of. If we are returning more than one element, then these should be wrapped into a single container element. Let us check that out in a sample example below:

import React from 'react';

class App extends React.Component {
   render() {
      return (
         < div >
            < h1 >Header< /h1 >
            < h2 >Content< /h2 >
            < p >This is the content!!!< /p >
         < /div >
      );
   }
}
export default App;

 

In the same example, we can provide a custom attribute in addition to the regular HTML code that has been written already. If we want to add a custom attribute, then we need to make use of the data- prefix. In the above example, let us add one custom property called data-mycustomattribute

 

import React from 'react';

class App extends React.Component {
   render() {
      return (
         < div >
            < h1 >Header< /h1 >
            < h2 >Content</h2>
            <p data-mycustomattribute = "somevalue">This is the content!!!</p>
         </div>
      );
   }
}
export default App;

 

Pro JSX:

In the examples above, we have just used simple HTML code additional to what can be achieved with a single “Hello, World!” React JS program. There are further constructs that could be used to do arithmetic operations, ternary operations, styling, and add some comments to your React programs. These can be achieved by using just the same sample program and replace the ordinary HTML code with an aforementioned construct from React.

React JS - Components

As we have already discussed earlier, any of the React code that you would want to write would have to go under a component. With this understanding, let us learn how to combine components in order to make the application well maintained. This approach will allow changing your component without even affecting the rest of the page.

Stateless Example:

In the example below, our first and foremost component is App and it is the owner of Header and Content. We are attempting to create Header and Content separately, and then adding it back to the JSX tree in the App component. In this requirement, there is only a change required in the App component. Let us check this example out, here comes App.jsx:

 

import React from 'react';

class App extends React.Component {
   render() {
      return (
         < div >
            < Header />
            < Content />
         < /div >
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         < div >
            < h1 >Header< /h1 >
         < /div >
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         < div >
            < h2 >Content< /h2 >
            < p >The content text!!!< /p >
         < /div >
      );
   }
}
export default App;

 

And we want this to be rendered onto the browser as well, hence we need to import this into the main.js file and then make a call to reactDOM.render() method. Let us check out main.js:

 

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

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

 

On running the above code, this is what the browser would be displaying.

 

React Js Components

 

Stateful Example:

In this example, we would follow the same main component App as earlier. The Header component is added like in the previous example without any change and also it doesn’t need any state related details. Instead of adding a Content tag, we would go ahead with a table implementation to add as many rows as we could dynamically add. Let us look at App.jsx:

 

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         data: 
         [
            {
               "id":1,
               "name":"Foo",
               "age":"20"
            },
            {
               "id":2,
               "name":"Bar",
               "age":"30"
            },
            {
               "id":3,
               "name":"Baz",
               "age":"40"
            }
         ]
      }
   }
   render() {
      return (
         < div >
            < Header />
            < table >
               < tbody >
                  {this.state.data.map((person, i) => <TableRow key = {i} 
                     data = {person} />)}
               < /tbody >
            < /table >
         < /div >
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         < div >
            < h1 >Header< /h1 >
         < /div >
      );
   }
}
class TableRow extends React.Component {
   render() {
      return (
         <tr>
            <td>{this.props.data.id}</td>
            <td>{this.props.data.name}</td>
            <td>{this.props.data.age}</td>
         </tr>
      );
   }
}
export default App;

 

Let us now look at main.js:

 

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));

 

On running this program, we would now be able to see that, instead of a stateless Content tag, we are now able to display dynamically added data with some state details attached to it.

 

Stateful Example

React JS - State

State can be defined as the place from where your value is coming from. We should always make sure that the state is kept as simple as possible, and also at the same time, we should always look for opportunities to reduce the number of stateful components. Let any number of components need their state value, we should always have a container component that holds the state details of all these components.

We can refer to the examples discussed in the previous section to understand more about State in the React JS world and also how it can be used.

React JS - Props

The only difference that one can identify between a State and Props is that Props are actually immutable objects. This is main reason why Container component always has a state defined, which gets updated or altered, whereas the children components should pass on data from State using Props.

Props Overview:

We are continuing the discussion that we initiated while understanding what Props are. Now, let’s check a simple example where we can use some Props values and how we can access them or render them on the browser. Let us take a look at App.jsx:

 

import React from 'react';
class App extends React.Component {
   render() {
      return (
         < div >
            < h1 >{this.props.headerProp}< /h1 >
            < h2 >{this.props.contentProp}< /h2 >
         < /div >
      );
   }
}
App.defaultProps = {
   headerProp: "Header from props...",
   contentProp:"Content from props..."
}
export default App;

 

Let us take a look at main.js:

 

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

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

 

When we run this on the browser, we would be able to see that the default Props constructor values are rendered on the browser.

 

React Js Props

 

Props Validation:

Validation on the properties is a useful technique to ensure the proper usage of components. It will also help reduce the number of bugs that we might get very late after crossing the development phases. Doing so, it makes your code pretty readable.

Let us take an example with the main component as App and have all the properties that are required. App.propTypes will be used for the necessary properties validation. If the properties are not using the right types, then we would receive a warning for the same. We can set App.defaultProps after specifying the validation patterns. Let us now take a look at App.jsx:

 

import React from 'react';

class App extends React.Component {
   render() {
      return (
         < div >
            < h3 >Array: {this.props.propArray}< /h3 >
            < h3 >Bool: {this.props.propBool ? "True..." : "False..."}< /h3 >
            < h3 >Func: {this.props.propFunc(3)}< /h3 >
            < h3 >Number: {this.props.propNumber}< /h3 >
            < h3 >String: {this.props.propString}< /h3 >
            < h3 >Object: {this.props.propObject.objectName1}< /h3 >
            < h3 >Object: {this.props.propObject.objectName2}< /h3 >
            < h3 >Object: {this.props.propObject.objectName3}< /h3 >
         < /div >
      );
   }
}

App.propTypes = {
   propArray: React.PropTypes.array.isRequired,
   propBool: React.PropTypes.bool.isRequired,
   propFunc: React.PropTypes.func,
   propNumber: React.PropTypes.number,
   propString: React.PropTypes.string,
   propObject: React.PropTypes.object
}

App.defaultProps = {
   propArray: [1,2,3,4,5],
   propBool: true,
   propFunc: function(e){return e},
   propNumber: 1,
   propString: "String value...",
   
   propObject: {
      objectName1:"objectValue1",
      objectName2: "objectValue2",
      objectName3: "objectValue3"
   }
}
export default App;

 

Let us now take a look at main.js:

 

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));

React JS - Component API

In this section, let us learn something about the React Component APIs. There are mainly three methods that we would want to discuss about -> setState(), forceUpdate() and ReactDOM.findDOMNode().

The setState() method will be used to update the state of the component. It will not replace the state of the component but only adds the changes to the original state.

The forceUpdate() method updates the component manually and this API helps in achieving just that.

The ReactDOM.findDOMNode() method is used for the DOM Node manipulations. For this to happen, we first need to import react-dom module.

React JS - Component Life Cycle

In this section, let us discuss in detail about the Component’s life-cycle. All the life-cycle methods are inside the component itself. The following are the sequence of events that happen during a request-response that is handled by a component. Let us take a look at each of these methods and also try to understand the concepts behind them:

1. componentWillMount is the method call, that gets called before rendering, on the client side and the server side alike.

2. componentDidMount is the method call, that gets called after the first time that it renders and this happens only on the client side. This is the place where all the AJAX requests and state or DOM updates occur. This method is generally used for integration purposes with other JavaScript frameworks or functions with delayed execution as like setInterval or setTimeout.

3. componentWillReceiveProps is the method call, that gets called along with props update and also before any other render request is received.

4. shouldComponentUpdate is a boolean method call that returns either false or true. In turn, it determines whether or not the component gets updated. This is set to true by default. If there is no necessity for the component to render with an update of either the state or props, then this can be returned as false always.

5. component will update is the method call, which gets called before rendering the component.

6. componentDidUpdate is the method call, which gets called after rendering the component.

7. componentWillUnmount is the method call, which gets called just after the component is unmounted from the DOM.

React JS - Events

Event handling is the topic that we would be discussing here. On the component examples that we have seen till now, let us try and add some onClick events to show the power of React JS Events. When you want to update the state of the Parent component from one of its child components, we can then make use of the event handler (updateState) on the Parent component and pass it as a property to the child component.
Let us get down to some code and how it fares (App.jsx):

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data updated from the child component...'})
   }
   render() {
      return (
         < div >
            <Content myDataProp = {this.state.data} 
               updateStateProp = {this.updateState}></Content>
         < /div >
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         < div >
            <button onClick = {this.props.updateStateProp}>CLICK</button>
            < h3 >{this.props.myDataProp}</h3>
         < /div >
      );
   }
}
export default App;

 

Let us see what needs to be put under the main.js file:

 

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

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

 

And when you run this sample piece of code, this is how the browser would render this:

 

React Js Event

React JS - Forms

In this section, let us go through how we can interact with forms in React JS. Let us consider a small example where we accept some values in a form and display it back to the User on the same form. This allows to update the state whenever the value in the input box has been changed. Here, indirectly, we are going to use the onChange event to achieve this. Let us now take a look at the relevant code (App.jsx):

 

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState(e) {
      this.setState({data: e.target.value});
   }
   render() {
      return (
         < div >
            < input type = "text" value = {this.state.data} 
               onChange = {this.updateState}  />
            < h4 >{this.state.data}< /h4 >
         < /div >
      );
   }
}
export default App;

 

Now let us see what goes into the main.js file:

 

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

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

 

And, when we run the above sample piece of code, this is how the browser renders:

 

React Js Form

React JS - Keys, Router

React Keys are useful when you are going to work closer with dynamically created components or when your lists are being altered by other users. Keeping the key value unique will enable you to keep your components identified uniquely. Now, with this understanding of keys, let us now go through what Routers are in React JS. Routers lets you route around your application via the links that we create to various components of the application. Let us now go through the step by step process of installation and a sample example to understand this.

1. Install the React JS Router component:

Installing the React JS Router component is as easy as running the following npm command, just the way we followed during the React JS environment setup.

C:UsersDesktopReactJSApplication>npm install react-router

 

2. Create the necessary components:

In this step, we shall be creating 4 components - one the main component (App) and the other three components are for the required traversal (Home, About, Contact). Let us look at these changes in the App.jsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'

class App extends React.Component {
   render() {
      return (
         < div >
            < ul >
            < li >Home< /li >
            < li >About< /li >
            < li >Contact< /li >
            < /ul >
            {this.props.children}
         < /div >
      )
   }
}
export default App;

class Home extends React.Component {
   render() {
      return (
         < div >
            < h1 >Home...< /h1 >
         < /div >
      )
   }
}
export default Home;

class About extends React.Component {
   render() {
      return (
         < div >
            < h1 >About...< /h1 >
         < /div >
      )
   }
}
export default About;

class Contact extends React.Component {
   render() {
      return (
         < div >
            < h1 >Contact...< /h1 >
         < /div >
      )
   }
}
export default Contact;

 

3. Add a Router to complete the flow:

Based on the components that we have created earlier, we have to add the routes as appropriate to the application. Instead of rendering the App component itself in the other examples, what we would be doing is to render the Route element itself. Let us take a look at these changes on the main.js file:

 

ReactDOM.render((
   < Router history = {browserHistory} >
      < Route path = "/" component = {App} >
         < IndexRoute component = {Home}  />
         < Route path = "home" component = {Home}  />
         < Route path = "about" component = {About}  />
         < Route path = "contact" component = {Contact}  />
      < /Route >
   < /Router >
), document.getElementById('app'))

 

Once the application is run, we will be able to see the links alone on the browser and when we choose to click on any of the links showcased (then you can see that the route has been changed).

 

React Js Router

React JS - Flux Concepts

As discussed earlier, Flux is a programming concept and a design pattern that talks about data being unidirectional. It means to say that the data that enters the application flows through it in one direction until it is rendered on the screen.

Let us now discuss a little bit regarding the flux elements that we would be discussing further with an example in detail. There are 4 elements that we can broadly classify into and discuss about these:

1. Actions − are sent to a dispatcher that will in turn trigger the required data flow.

2. Store - Stores are the places where the application state and logic are held. Each and every store maintains a particular state and this will be updated once when it’s needed.

3. Dispatcher − can be understood as the Central Hub of the application. All the data is dispatched and sent to the stores.

4. View - The View is the element that receives the data from the stores and renders it on the application.

 

React JS - Using Flux

In this section, let us try understanding the Flux usage based on the concepts discussed in the previous section. To implement Flux pattern in React JS, we will be using the Redux framework. Hence the first step here would be to install the Redux framework and then integrate with the React JS framework. Installation of Redux can be done via a command line tool command shown below:

<strong>C:Users<Your Username>DesktopReactJSApplication>npm install react-redux --save</strong>

Once the installation is concluded, we then have to create the files and folders that are required for our application - which would typically be our actions, reducers, and components.

C:Users<Your Username>DesktopReactJSApplication>mkdir actions<br>C:Users<Your Username>DesktopReactJSApplication>mkdir components<br>C:Users<Your Username>DesktopReactJSApplication>mkdir reducers<br>C:Users<Your Username>DesktopReactJSApplication>type nul > actions/actions.js<br>C:Users<Your Username>DesktopReactJSApplication>type nul > reducers/reducers.js<br>C:Users<Your Username>DesktopReactJSApplication>type nul > components/AddTodo.js<br>C:Users<Your Username>DesktopReactJSApplication>type nul > components/Todo.js<br>C:Users<Your Username>DesktopReactJSApplication>type nul > components/TodoList.js

Once the necessary files and folders are created, the next step then would be to fill these files with the necessary code snippets to get our application working. Actions are the JavaScript objects which use the type property in order to inform about the data that needs to be sent to the store. Let us now check our actions.js code:

 

export const ADD_TODO = 'ADD_TODO'

let nextTodoId = 0;

export function addTodo(text) {
   return {
      type: ADD_TODO,
      id: nextTodoId++,
      text
   };
}

 

Once the required actions are created, we then move on to creating our reducers. These reducers specify the changes that are supposed to be happening on the application. A reducer is a function that takes in two different parameters (state and action) to determine and return the updated state. Let us now check out reducers.js code:

 

import { combineReducers } from 'redux'
import { ADD_TODO } from '../actions/actions'

function todo(state, action) {
   switch (action.type) {
      case ADD_TODO:
         return {
            id: action.id,
            text: action.text,
         }
      default:
         return state
   }
}
function todos(state = [], action) {
   switch (action.type) {
      case ADD_TODO:
         return [
            ...state,
            todo(undefined, action)
         ]
      default:
         return state
   }
}
const todoApp = combineReducers({
   todos
})
export default todoApp

 

As we have discussed, a Store is the place where it holds the application’s state details. Once you have a reducer, it is very quick to create a Store. Let us now check our main.js code implementation:

 

import React from 'react'

import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'

import App from './App.jsx'
import todoApp from './reducers/reducers'

let store = createStore(todoApp)
let rootElement = document.getElementById('app')

render(
   < Provider store = {store} >
      < App  />
   < /Provider >,
	
   rootElement
)

 

The component “App” is the actual root component of the application that we are looking at. In this application, only the App component is the one that should be aware of Redux presence. Let us now take a look at its code as well for this example (App.jsx) code:

 

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTodo } from './actions/actions'

import AddTodo from './components/AddTodo.js'
import TodoList from './components/TodoList.js'

class App extends Component {
   render() {
      const { dispatch, visibleTodos } = this.props
      
      return (
         < div >
            < AddTodo onAddClick = {text =>dispatch(addTodo(text))}  />
            < TodoList todos = {visibleTodos} />
         < /div >
      )
   }
}
function select(state) {
   return {
      visibleTodos: state.todos
   }
}
export default connect(select)(App);

 

Once all of these are done, then we can look at the other components that are required. Let us now take a look at components / AddTodo.js code:

 

import React, { Component, PropTypes } from 'react'

export default class AddTodo extends Component {
   render() {
      return (
         < div >
            < input type = 'text' ref = 'input'  />
				
            < button onClick = {(e) => this.handleClick(e)} >
               Add
            < /button >
         < /div >
      )
   }
   handleClick(e) {
      const node = this.refs.input
      const text = node.value.trim()
      this.props.onAddClick(text)
      node.value = ''
   }
}

 

Let us now take a look at the components/Todo.js code as well:

 

import React, { Component, PropTypes } from 'react'

export default class Todo extends Component {
   render() {
      return (
         < li >
            {this.props.text}
         < /li >
      )
   }
}

 

components/TodoList.js code:

 

import React, { Component, PropTypes } from 'react'
import Todo from './Todo.js'

export default class TodoList extends Component {
   render() {
      return (
         < ul >
            {this.props.todos.map(todo =>
               < Todo
                  key = {todo.id}
                  {...todo}
                />
            )}
         < /ul >
      )
   }
}

 

Once, when we run the application, this is how it gets rendered on the browser.

 

Reactjs using flux

React JS - Animations

In this section of the article, we will go through the animations that can be achieved using React JS Animations. For this to happen, we are required to install a module ‘React CSS Transitions Group’. The following command should suffice to install this:

C:UsersDesktopReactJSApplication>install react-addons-css-transition group

Once this installation is successfully done, then you’ll need to add some files that are required for creating any animations using React JS. Let us now create the style.css file from the command line tool itself.

C:UsersDesktopReactJSApplication>type nul > css/style.css

Corresponding change has to be included in the index.html as well:

 

< !DOCTYPE html >
< html lang = "en" >
   <head>
      < link rel = "stylesheet" type = "text/css" href = "./style.css" >
      < meta charset = "UTF-8" >
      < title>React App</title >
   < /head >
   <body>
      < div id = "app">< /div>
      < script src = 'index_bundle.js'>< /script>
   < /body >
< /html>

 

Here, we will be creating a normal React component. Let us now take a look at the (App.jsx) file:

 

import React from 'react';
var ReactCSSTransitionGroup = require('react-addons-css-transition-group');

class App extends React.Component {
   render() {
      return (
         < div >
            < ReactCSSTransitionGroup transitionName = "example"
               transitionAppear = {true} transitionAppearTimeout = {500}
               transitionEnter = {false} transitionLeave = {false} >
					
               < h1 >My Element...< /h1 >
            < /ReactCSSTransitionGroup >
          < /div >      
      );
   }
}
export default App;

 

Let us now take a look at the (main.js) file:

 

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

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

 

Let us add some simple CSS animation to the newly created style.css file:

 

.example-appear {
   opacity: 0.04;
}
.example-appear.example-appear-active {
   opacity: 2;
   transition: opacity 50s ease-in;
}

 

Once we start the server, we should be able to see the browser render something similar to this:

 

React Js Animations

React JS -Higher Order Functions

Higher Order Functions (HOFs) are the JavaScript functions that provide additional functionalities to the existing React component. These functions always take input values and provide return values according to the input data. That means, if the input values are changed, then the HOFs are re-run to provide the resultant return value based on the input values.

A Higher Order Component, abbreviated as HOC is a wrapper around a React component and provides additional data as input. To be very precise, it is also a function which takes a component as input and returns a totally different component which internally wraps the original component.

Let’s understand this with an example and also check how this actually works. MyHigherOrderFunction is a HOF which is used to pass the data to MyComponent. The function that we have created, then takes MyComponent and strengthens it with the data “newlyProvidedData” - returns the modified component which will in turn be rendered on to the browser.

 

import React from 'react';

var newData = {
   data: 'Data from HOC...',
}

var MyHOC = ComposedComponent => class extends React.Component {
   componentDidMount() {
      this.setState({
         data: newlyProvidedData.data
      });
   }
   render() {
      return <ComposedComponent {...this.props} {...this.state} />;
   }
};
class MyComponent extends React.Component {
   render() {
      return (
         < div >
            < h1 >{this.props.data}< /h1 >
         < /div >
      )
   }
}

export default MyHigherOrderFunction(MyComponent);

 

When we run this on the browser, this will be shown:

 

Reactjs higher order components

React JS - Best Practices

In this section, we will go through the best practices that one can imbibe to write better code. These techniques will help you stay consistent during your application development phase.
Let us go through these one after the other to understand them well:

1. Usage of state can be avoided to the maximum and a good practice is to centralize the state and pass down the tree as props. A container element can be set around the properties which will ensure that the state is held intact. One of the best ways to tackle states in React JS applications is to use Flux pattern.

2. Always define PropTypes as they will help you in tracking all the props in your application. This always forms a reference to the other developers working on the same project.

3. React JS recommends the usage of Single Responsibility Principle, meaning, that there should be a single component that handles the responsibility of a functionality. It is suggested to refactor code wherever necessary so as to ensure that there are no more than one functionality per component.

4. Earlier React JS versions provided support for reusable functionalities, which is no longer available - hence the usage of Higher Order Components (HOC) is suggested.

Conclusion

In this article, we have covered a lot of topics ranging from introduction to React JS, advantages, limitations, features, installation procedures, various components, and best practices. React JS is a wonderful JavaScript library that helps in both the server side and client side scripting and has got a lot of following in the developers' community. It has backing from Facebook where there is active development going on to make it a better UI framework altogether. We have put in great amount of effort in putting most of the details here to precision. If you find anything incorrect, please let us know in the comments section for us to correct the same.