Advantages of React JS: Open-source JavaScript Library

Creating dynamic UI with React JS

Due to the growing popularity of reactive approaches to software development, programmers are now turning with more and more interest to React JS - open-source JavaScript library that solves problem of fast visualization of a big dataflow and simplifies creation of interactive user interfaces.

When it is needed to display dynamic content, template engines are used. They work pretty simple: to the existing template a specific set of data is applied and some of dataset representation is obtained. If data is changed, it has to be displayed in a representation. A programmer needs to write the code which alters representation and synchronizes data changes in one. But, if we already have a template, why don’t we use it? The idea to use template not just at initial rendering but after every data change is fundamental in React JS.

However, for displaying data changes, programmers have to manipulate DOM tree and write code which displays all updates in different specific cases. React JS library is aimed at solving this problem.

React JS: getting started

Let’s take a look at the example of the simplest app written in JavaScript:

<!DOCTYPE html>
<div id="app"></div>
<script>
  // create DOM-node
  var a = document.createElement("a");
  a.setAttribute("href", "http://anadea.info");
  a.value = "Click me";

  // mounting into document
  document.getElementById("app").appendChild(a);
</script>

There is a page which includes one element div, and with the help of usual DOM API, element "a" is created, with attribute href and some link (http://anadea.info), with text «Click me» to display link. Such construction is inserted into the document by appendChild. Consequently, we get a page with the link to our site.

We do the same when we use React – construct elements using syntax: create unit as "a" with an appropriate set of attributes and definitions that is inside the element.

<!DOCTYPE html>
<div id="app"></div>
<script>
  // create DOM-node
  var a = React.createElement("a",
    {href: "http://anadea.info"},
    "Click me");
  // mounting into document
  React.render(a, document.getElementById("app"));
</script>

Inserting into the page is very similar – in this case we render our element.

A basic function that creates all elements is a React.createElement. There are standard elements available such as div, span, p, strong and etc. With React syntax we can create complex constructions by simple nesting functions instead of using appendChild and insertBefore in DOM API. It makes code more declarative. For standard elements, there is available a short note like React.DOM.div.

React.createElement(<element>[, <properties>[, <children>...]]) 
React.DOM.<element>([<properties>[, <children>...]])  

Creating components

One of the main features of React is the possibility to create own components from others easily. At the same time, it can be used as standard components created earlier. For instance, the component that contains a picture, a tag "a" and a text looks as following:

var Link = React.createClass({
  render: function() {
    return React.DOM.a(
      {href: "http://anadea.info"},
      React.DOM.img({src: "/assets/logo.png"}),
      "Click me"
    );
  }
});

React.render(
  React.createElement(Link),
  document.getElementById("app")
);

All elements are JavaScript objects, and it is necessary to describe them as a class for creating own associated elements. Such class has to contain a render method which represents an internal structure of the element. In React we have a possibility to combine simple or complex elements. It looks like getting bigger partials from the small ones and then combining them into the entire application.

var Link = React.createClass({
  render: function() {
    return React.DOM.a(
      {href: this.props.url},
      React.DOM.img({src: "/assets/logo.png"}),
      this.props.title
    );
  }
});

React.render(
  React.createElement(Link,
    {url: "http://anahoret.com",
    title: "Click me!"}
  ),
  document.getElementById("app")
);

We can create custom elements that adapt to our needs. Every element attains a dictionary of properties at the creation. It is available in the form of group code as this.props. For example, this is how the element Link gets the properties url and title:

var Link = React.createClass({
  render: function() {
    return React.DOM.a(
      {href: this.props.url},
      React.DOM.img({src: "/assets/logo.png"}),
      this.props.children
    );
  }
});

React.render(
  React.createElement(Link,
    {url: "http://anahoret.com"},
    "Click ",
    React.DOM.strong(null, "me!")
  ),
  document.getElementById("app")
);

Inserted elements are available as this.props.children. In the example above this property contains two definitions: text "Click" and element strong with text "me!".

Properties of components are immutable, i.e. they can’t be changed. For changeable attributes a state exists which is also a dictionary. We can read values by looking at an attribute this.state. The existing method can be altered by this.setState.

Component's lifecycle

All components of React are groups with one obligatory method – render. The lifecycle of a component consists of three phases: mounting into DOM tree, updating and unmounting. The component comprises methods for each phase.

The following methods are available in the mounting phase:

  • getInitialState. It can be used to set the component’s initial conditions;
  • componentWillMount. It is called before mounting for setting network connection or for sending ajax request;
  • componentDidMount. It is useful to make extra DOM manipulation, call third-party library, or similar routines.

These methods are invoked once during the component’s lifecycle. Renders of the updating phase are: componentWillRecieveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate. Every time when the component alters, a componentDidUpdate is called. It can be used for calling other libraries as well. The last phase is unmounting in which the componentWillUnmount method is available. It is preferred for actions opposite to the mounting phase. Besides the above-mentioned elements, the component can have any user-defined method.

ReactJS - How it works

Virtual DOM

Each component displays its properties and state in a VirtualDOM structure. React translates virtual Dom to the real DOM. New virtual DOM is built every time any properties or component’s states are changed. It compares them with what we have in browser, reckons a minimal set of necessary alters and applies them. React isolates us not only from DOM, but also from events which happen in it, and introduce synthetic events instead of the latter. Objects of those events don’t depend on a current browser since React reveals distinctions between browsers and fills in missing attributes.

Let’s look at a simple example how to use React:

var List = React.createClass({
  render: function() {
    return React.DOM.ul(null,
      this.props.children.map(function(child, index){
        return React.DOM.li(null,
          child,
          React.DOM.button({onClick: this.props.onDeleteItem.bind(null, index)}, "X")
        );
      }, this)
    );
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      items: []
    };
  },

  render: function() {
    return React.DOM.div(null,
      React.createElement(List, {onDeleteItem: this.onDeleteItem}, this.state.items),
      React.DOM.input({ref: 'new_item'}),
      React.DOM.button({onClick: this.onAddClicked}, 'Add')
    );
  },

  onAddClicked: function() {
    var newItems = this.state.items.slice();
    newItems.push(this.refs.new_item.getDOMNode().value);
    this.setState({items: newItems});
  },

  onDeleteItem: function(index) {
    var newItems = this.state.items.slice();
    newItems.splice(index, 1);
    this.setState({items: newItems});
  }
});

If you execute this code you will get the following:

Using React

The code represents an edit list with an option to delete or add a line. It consists of two components – "List" and "App". A list represents list’s elements and arranges the "Remove button" next to each of them (lettered "x"). The app represents List, an input box and a button to add a new element to the list. A data of the list is kept in a state of App’s component when the list is stateless. Initially the list is empty what is noticeable from getInitialState method’s code. Moreover, there are two additional functions, which add and remove elements from the list.

JSX

In addition to React, there are transpilers (JSXTransform, Babel) which provide syntax constructions for a more concise code. This language is called JSX. A render looks like this:

  render: function() {
    return (
      <div>
        <List onDeleteItem={this.onDeleteItem}>
          {this.state.items}
        </List>
        <input ref='new_item' />
        <button onClick={this.onAddClicked}>Add</button>
      </div>
    );
  }

The code of our components can run out of browser, because it’s not connected to DOM directly. It can be used for a server-side as a template engine, which makes writing isomorphic apps possible (apps which can run both on the server and the client). It means that we can use all beauty of NodeJS speed while writing tests. If the components don’t have State, then they reduce to simple functions. In other words, we pass on sample qualities to the element when we create it, run render and get DOM – this is one of the simplest form of tests. Transformation of data to virtual DOM always goes one way. That’s why tests are very simple even for the most difficult components.

Why React is a right choice?

It offers a simple model which works well with a big dataset, displays it quickly and allows fast editing. It can be tested easily. State always is changeable at certain places. That’s why it is easy to see how HTML will look like. If we combine React with any Flux libraries (Redux, McFly, Barracks, Fluxxor) we’ll get a full app architecture. Also, React is a platform on which new frameworks can be built – React Native, Grail, Om and others.


React JS and Rails, our favorite backend framework, are the technologies which well go together, so for us it was obvious that we should have React JS on our skillset. We hope our tutorial, along with other existing React JS documentation and guides, will help you to decide if you should give it a shot in your project.

Get in Touch