React.js, UI Library from Facebook for Fast Single Page Applications

P. Madhanasekaran

Introduction:

React is a JavaScript library for creating user interfaces and open sourced by Facebook and Instagram team in 2013.It is a library for Single Page Applications, similar to frameworks like Angular, Backbone, Ember etc. It seems to have been influenced by persistent data structures from Clojure and other functional languages and applied the same for DOM manipulation. What is DOM or Document Object Model? DOM is the structure of HTML or XML elements that make up a web page. The Browser renders the page from the DOM tree. When a user interacts with a web page the changes he makes is carried out immediately in the DOM tree and the browser re-renders the page and this re-rendering is slow. This is the case, whether we use for user–interaction JavaScript or a library like JQuery or framework like Backbone. How then React.js and other newer JavaScript re-render DOM faster? In React UI is composed from components which are abstractions over DOM elements. When user interacts, the props or state in components changes .Now React constructs a virtual DOM and compares the virtual DOM   to real DOM tree and only those DOM elements whose state has changed are re-rendered. This selective re-rendering of only those DOM elements where some change has happened makes re-rendering faster. DOM manipulation is inherently slow and the indirection introduced by React reduces the amount of changes to be made in the DOM tree and this results in rapid re-rendering.

One might think of React as the “View” in the “Model-View-Controller” pattern. React’s main goal is to make development of UI components easy and modular. It is intended to ease the process of building large applications using data that change over time.  React was created by Jordan Walke, a software engineer at Facebook, with the influence of XHP, a PHP-based component system that is still in use at Facebook, but also by functional programming ideas. Pete Hunt wanted to use React at Instagram, so he pushed to extract React from Facebook-specific code and open source it. In other words React.js is a library for building composable user interfaces from components. React components can have state. React handles mapping from input to state changes and it renders components.  In this sense it does everything a MVC does. There is also a huge eco-system/libraries around it. React gives you lightweight virtual DOM, powerful views without templates, uni-directional data flow and explicit mutation. A React App consists of reusable components. Components make code reuse, testing and separation of concerns easy. Components are influenced by functional paradigm and React uses composition of components rather than inheritance from OOPs; but the object oriented- paradigm is not completely done away with. Component is actually class in React. Components have mutable states and props. It is suggested to use immutable libraries with React for better performance.  In React documentation it is mentioned that “Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like Clojure”. It also suggests users to have a look at Immutable.js library from Facebook. Shared mutable state is the root of all evil - Pete Hunt in React.js Conf 2015. Immutable objects can save us all a headache and improve the rendering performance.

Development Environment

It is rather difficult to create a React project from scratch, as react.js is a small library and other libraries may have to be used. One work-around is downloading the react-starter kit and writing our code within the root folder of the kit. Another way is using Node Package Manager to download the necessary dependencies. The third way is using one of the React Project Generators and there are a number of them. Enclave, nwb, react-boilerplate are among those from the community. With the collaboration and contribution from the authors of these generators, the official generator “create-react-app” has come out and we can use the same. We will see it little later. Now we will use the starter kit.

Download react-15.0.1 which is available as a zip file. If you unzip it to a directory of your choice you can see the following folders and files

You can create the helloworld.html with some editor in the root folder.

If you open the file with chrome you can see

Hello, Venkat!

We will see how things worked.

/helloworld.html
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8" /> <title>Hello React!</title> <script src="build/react.js"></script>
// these files are available in build folder
<script src="build/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-       
core/5.8.34/browser.min.js"></script>    //-----1)
</head> <body> <div id="example"></div> <script type="text/babel">   //-------1) ReactDOM.render(  //---------3) <h1>Hello, Venkat!</h1>,    // React Component using JSX document.getElementById('example') //--------2) ); </script> </body> </html>
  • React does not use any template; it uses an XML extension of JavaScript called JSX.As browsers can not recognize JSX, the file “browser.js”  from babel is required and used. A react component can be created using JSX.JSX is basically embedding some HTML tags in JavaScript.(Java users can recall coding servlets). You can also use JavaScript without JSX. But JSX seems to have been preferred by React Community.
  • We tell the library to render the result in the <div> example -that is where to mount the component
  • React components implement a render() method that takes input data and returns what to display. It returns a single child element. [The render() function should be pure, meaning that it does not modify the component state. It should examine this.props and this.state and

To a JavaScript programmer there is nothing new in the above code except some HTML embedded in JavaScript. We will see more about the same in the next sample. Components in React are abstractions over HTML elements that enable React to intercept them and create the JavaScript object virtual DOM and apply the “diffing” and send only the changes in   elements to the Browser for DOM re-rendering or re-painting. This also helps in less code, when building your UI with them.
Another Example: To store data to be displayed in HTML the components in React has two properties 1]props 2] state. In this example we will see how to use “props” 

index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01    Transitional//EN">

 

<html> <head> <script src="build/react.js"></script> <script src="build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js">
</script>
<title>React file</title> </head> <body> <div id="example"></div> <script type="text/babel"> var MyComponent = React.createClass({  //----------1)
render: function(){ return <div> <h1>{this.props.text}</h1>  //-------3) <p>{this.props.children} </p> </div>; } });
ReactDOM.render(<div>    //--------2) <MyComponent text= "Hello Venkat"> This is a Hello. </MyComponent>
<MyComponent text="How are You"> This is a how are you. </MyComponent>
<MyComponent text= "Goodbye"> This is a good bye. </MyComponent>
</div>
,   document.getElementById('example')
);
</script> </body> </html> 
  • A custom component is created using createClass method. A component class is created, with given a specification. A component should implement a render method which returns one single child.It you want to return more than one DOM element wrap them in <div> .One thing that makes components different than standard prototypal classes is that you don't need to call new on them. In other words when creating a component class by invoking React.createClass(), you should provide a specification object that contains a render method and can optionally contain other lifecycle methods. When called, it should examine this.props and this.state and return a single child element. Any thing put within curly braces{} in JSX is executed as JavaScript.
  • Different instances of the component MyComponent are put within a <div>.The different instances have different values for the text property and different children.As mentioned above the render() method can return only a single DOM element and to return multiple DOM elements they should be wrapped within a HTML tag like <div>
  • “this.props” is able to access the text property in the instances but also the children of instances. For this, when parent components are rendered, they have access to a special property, this.props.children

State

As mentioned above, components in React.js have two properties used to store data to be displayed in HTML: the state and props objects. They're both plain JavaScript objects and both can be used in the render function of your components. We saw how the props is used in the earlier sample. The “state” is useful when a property may change. For example, the user clicks a button, types in an input field, or receives new data from a WebSocket server. These events would update a property in the component's state by calling setState, and the update is rendered in HTML.
Look the example which uses events and state to track clicks and update the rendered output below:

Counter.html
<!DOCTYPE html>
<html> <head> <meta charset="UTF-8" /> <title>Hello React!</title> <script src="build/react.js"></script> <script src="build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js">
</script>
</head>
<body>
<div id="container"></div> <script type="text/babel">
var Counter = React.createClass({ getInitialState: function () {   //--------1] return { count: 0 }; },
handleClick: function () {  //---------3] this.setState({         //--------2] count: this.state.count + 1, });
},
render: function () { return ( <button onClick={this.handleClick}>            //--------3] Click me! Number of clicks: {this.state.count} </button> ); } }); ReactDOM.render( <Counter />,
document.getElementById('container')
);

 

</script> </body> </html>

If you open the file in a Browser you can see the following output:

Click me.Number of clicks 0

If you click on this you can see the counter increments.

1] Within the component, getIntialState lifecycle method is used to set the initial state.
2] the state can be accessed with {this.state.}
3] wrapping the event within the component enables React to intercept the event and the event goes through virtual DOM.

Generators

 The generators are helpful tools to get started with React and set the project up and running quickly. Create React App is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration. But to install it and use it ,Node.js 4.x or higher is required. If the Node.js in your system is lower you can un-install it and install a higher version. But that is not enough. You have to update NPM with the following command.
npm install npm@latest –g                   

Now youcan install the generator with the following command
npm install -g create-react-app
After the generator and the dependencies are installed you can use it. 
The important dependencies are:
Generate a project
You can generate the project hello-world with the following command
create-react-app hello-world.

This will take a while as npm installs the transitive dependencies, but once it’s done, you will see a list of commands you can run in the created folder:

Run

npm start

to launch the development server. The browser will open automatically with the created app’s URL.

The code for the generated /src/App.js is given below:

/src/App.js

import React, { Component } from ‘react’;
      import logo from ‘./logo.svg’;
      import ‘./App.css’;

 

class App extends Component {  //---------------------1) render() { return ( <div className=”App”>    //-----------------2) <div className=”App-header”> <img src={logo} className=”App-logo” alt=”logo” /> <h2>Welcome to React</h2>
</div>
<p className=”App-intro”> To get started, edit <code>src/App.js</code> and save to reload. //-------3)
</p> </div> ); } }export default App;

  1. The syntax is ES6.No “createClass” seen earlier,  but only “ extends Component” .
  2. This is JSX. Though they call it extending JavaScript with xml syntax for easy creation of DOM tree, to the users familiar with other languages it may appear to be embedding HTML in JavaScript code, though there are some small differences between JSX and HTML, as pointed out under JSX Gotchas in React documentation.
  3. This is what displayed in the Bowser. If you add HELLO GANESH and save it you can it is added the Bowser display without any refresh. Only the input we gave now changes and the earlier display remains as it is.

Any code is not required from us to manage this behavior. React figures it out for you and does the right thing. React does not manipulate the DOM unless it needs to. It uses a fast, internal virtual DOM to perform diffs and computes the most efficient DOM mutation for you. The inputs to this component are called props — short for "properties". They're passed as attributes in JSX syntax. You should think of these as immutable within the component, that is, never write to this.props. Components are Just like Functions. React components are very simple. You can think of them as simple functions that take in props and state and render HTML

Index.html: The file is given below:

/index.html

<!doctype html>
      <html lang="en">
      <head>
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>React App</title> </head> <body>
<div id="root"></div> </body> </html>

The generated index.js which puts together things is given below:

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

 

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

Create React App uses both Webpack development server and Babel JavaScript compiler under the hood.

One more sample using generator

Execute
create-react-app groceryList
After the project is generated you can modify App.js as under:

/src/App.js
import React, { Component    } from 'react';
      import logo from    './logo.svg';
      import './App.css';

 

class App extends Component { render() {  //-------------1] return ( <ul>
<ListItem quantity="5">Bread</ListItem>  <ListItem quantity="8">Eggs</ListItem> <ListItem quantity="12">Cake-Plain</ListItem>
</ul> ); } }
class ListItem extends Component { render() { return ( <li> {this.props.quantity}× {this.props.children}  //-------2]                      
</li> ); } } export default App;

1] Within the render method of first component multiple instances of another component are created. This is one way to pass dynamic data to JSX.
2] When this component is rendered see how dynamic data is passed to its attributes”. The quantity is an attribute. data within opening and ending tags of <ListItem>are passed as “children” property

When you run
npm start
the browser will start and show the following:

  • 1× Bread
  • 6× Eggs
  • 12× Cake

Conclusion

React team prefers to call it a UI library but it has a huge eco-system around it.DOM rendering is inherently slow; but React makes this faster by selectively re-rendering only those DOM elements that have changed after initial rendering. When user inputs some data React creates a virtual DOM and this virtual DOM is compared with the real DOM and the differences are batched and only minimal changes are re-rendered. React has been influenced by the functional paradigm in building the UI layer by composing components. But data is passed to these components through mutable props and states. Attention is invited to the talk “React.js Super-fast Single Page Web Applications” by Pratik Patel available on YouTube. Best practices suggest use of the library Immutable.js or a language like Clojurescript which supports persistent/immutable data structures.  Immutable is an object whose state cannot be modified after it is created. Immutable objects can save us all a headache and improve the rendering performance with their reference-level equality checks. Flux provides a clean way to store and update our application's state and trigger rendering when it's needed. There are a number of Flux libraries and Redux is one of them. Redux evolves the ideas of Flux but avoids its complexity by taking cues from Elm. ClojureScript has wrappers for React like Ohm, Reagent etc. With the immutable data structures in ClojureScript these wrappers perform better than React.js. We will see more about these later.








}