Introduction to React.js

written by devangelist on December 23, 2014 in Frameworks and Javascript and React with no comments

It feels like a new JavaScript framework is created almost daily, but there are only a few that draw enough interest from developers to stand a chance in the market. Yesterday everybody was talking about Angular and Ember, many people today choose React. And not only because Facebook is behind that framework, but because React offers some unique properties that have been forgotten by other competitors.

Reactjs was created by Facebook and is not only used by its founders, but also by other platforms like Instagram, which has been completely written in React. The framework is supposed to help create interactive, state-oriented and reusable UI components.

React beats SEO

The isomorph framework cannot only be used on the client, but on the server side as well. This can be an important factor, because even though search engines like Google are capable of understanding and interpreting JavaScript, this is still a rather theoretical approach.

If a website is highly depending on traffic coming from Google, hopefully no one will get the idea to load it onto the client completely. Maybe this theory will change in a few years, but until then the website needs to be rendered on the server.

Virtual DOM

React tries to keep DOM manipulation as minimal as possible. Using Virtual DOM only certain sub-trees of nodes will be rendered depending on their state changes. This is best explained by an example:

Let’s say there is a model. And I am not talking about a (not-so-top) model like Heidi Klum. All relevant properties of that model (eyes, body mass, …) are being mirrored onto the current state of the model. This is the same thing that React is doing with the DOM.

If this model really wants to become a top model and doesn’t want to give up certain procedures and a strict fitness program, React would do the following:
At first all changes that are currently happening will be identified (reconciliation). After that the DOM is being updated.

React would not create a completely new model, but would only change certain aspects of the body. If a DOM element is supposed to be re-rendered while the parent element has not received any changes, it will not be touched.

Yet React always works with a fake-DOM which enables the rendering to be done by the server.

Getting started

On the getting started page you can either download a starter kit or get right into it using JSFiddle.

All you need to get started is react.js and JSXTransformer.js. The JSX components will be created in a type="text/jsx" script block.

<!DOCTYPE html>
<html>
  <head>
    <script src="build/react.js"></script>
    <script src="build/JSXTransformer.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/jsx">
      React.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

The React JSX code can (and should) be saved in two separate files. Using webpack or Browserify can be recommended.

React’s concept is based on components. For example:

React.renderComponent(
  React.DOM.h1(null, 'Hello, world!'),
  document.getElementById('example')
);

Or using JSX:

/** @jsx React.DOM */
React.renderComponent(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

Mixing JavaScript and HTML might look a bit unusual at first, but will start to look better after a few examples.

JSX – Javascript XML Syntax

These aren’t real HTML elements, but XML like elements. But since it is still JavaScript, attribute names that are not recommended for XML like class and for are being replaced by JSX equivalents className and htmlFor. (JSX Gotchas)

React JSX transforms the XML like syntax to native JavaScript. But it can only identify and transform snippets that begin with the following comment:

/** @jsx React.DOM */

An example for transforming XML to JavaScript:

var AComponent;
// Input (JSX):
var app = <AComponent text="Hello" />;
// Output (JS):
var app = React.createElement(AComponent, {text:"Hello"});

Components

Custom components are being created by the createClass method:

var AComponent = React.createClass({
    render: function(){
        return (
            <h1>Hello, world!</h1>
        );
    }
});

The component can be stated as the first argument in the already presented renderComponent method:

React.renderComponent(
    <AComponent/>,
    document.getElementById('example')
);

Yet React is a lot more fun if own components are being extended by attributes (Props). These can be used within the component via this.props:

var DayComponent = React.createClass({
    render: function(){
        return (
            <h1>Today is {this.props.day}!</h1>
        );
    }
});

React.renderComponent(
    <DayComponent day="Sunday" />,
    document.getElementById('example')
);

Component specs & lifecycle

In React.createClass() an object specification is necessary. This specification includes one required entry render and several other optional methods for the component specification:

  • getInitialState: The return will be used as the initial state.
  • getDefaultProps:: If props isn’t being used, they are used as fallback.
  • mixins: An array of objects in order to bring functionality to multiple components.

And also for the component lifecycle:

  • componentWillMount: Is being called once each on both the client and server side.
  • componentDidMount: Is only being called on the client side after the rendering. At this point the component already has a DOM representation which can be accessed via this.getDOMNode().
  • shouldComponentUpdate: Should the component be refreshed? Is being called before rendering if props or state have changed.
  • componentWillUpdate: Directly before the rendering.
  • componentDidUpdate: Directly after the rendering. In order to start DOM operations right after an update.
  • componentWillUnmount: Is being called by the DOM before unmounting a component. Is used for cleaning up DOM elements that were created by componentDidMount.

There are several other methods. For detailed information please have a look at the React component specs documentation.

State

The initial state can be set via getInitialState.
Using the setState method this state can be refreshed and is triggering a UI update.

var DayComponent = React.createClass({
    getInitialState: function(){
        return {
            day: "Tuesday"
        }
    },
    render: function(){
        return (
            <h1>{this.state.day}</h1>
        )
    }
});

Events

React uses SyntheticEvent, a cross browser wrapper for native browser events. Just like the same interfaces like the natives events (stropPropagation(), preventDefault, …) these are supposed to work identically with all browsers.

In React events are being added as properties of components and trigger a method that is defined in the object specification:

var DayComponent = React.createClass({
    getInitialState: function(){
        return {
            day: "Tuesday"
        }
    },
    setSunday: function() {
        this.setState({
            day: "Sunday"
        });
    },
    render: function(){
        return (
            <h1>{this.state.day}</h1>
            <button onClick={this.setSunday}>Set sunday</button>
        )
    }
});

Data Flow

Unlike the two-way binding of frameworks like Angular, React uses the Von Neumann model of computing and the data flows unidirectional from the owner to the child. That means that the parent component needs to pass on the state to the whole chain underneath itself using this.props.

Even if two-way-binding is possible in React it should be used with care (for example in forms – if the state needs to be adjusted depending on the user’s entries).

In order to depict this scenario React would need to listen to a change-event, get the information from a (usually) DOM and pass it on to the component using setState().

/** @jsx React.DOM */

var DayComponent = React.createClass({
  getInitialState: function(){
     return {
       initialItems: [
         "Monday",
         "Tuesday",
         "Wednesday",
         "Thursday",
         "Friday",
         "Saturday",
         "Sunday"
       ]
     }
  },
  componentWillMount: function(){
    this.setState({items: this.state.initialItems})
  },
  render: function(){
    return (
      <div>
        <DayList items={this.state.items}/>
      </div>
    );
  }
});

var DayList = React.createClass({
  render: function(){
    return (
      <ul>
      {
        this.props.items.map(function (item) {
          return <li>{item}</li>
        })
      }
      </ul>
    )  
  }
});

React.renderComponent(<DayComponent/>, document.getElementById('example'));

Attention: Within the map function this does not refer to the component, but to the anonymous function and therefore window.
However if a click event is supposed to be bound on a method that was defined in a component, the context can be made either using .bind(this) at the end of the anonymous function or by setting a variable _this outside of the function:

handleDayClick: function(i) {
  console.log(this.props.items[i]);
},
render: function(){
  return (
    <ul>
    {
      this.props.items.map(function (item, i) {
        return (
          <li onClick={this.handleDayClick.bind(this, i)}>
            {item}
          </li>
        )
      }.bind(this))
    }
    </ul>
  )  
}

Or using _this:

render: function(){
  var _this = this;
  return (
    <ul>
    {
      this.props.items.map(function (item, i) {
        return (
          <li onClick={_this.handleDayClick.bind(this, i)}>
            {item}
          </li>
        )
      })
    }
    </ul>
  )  
}

Conclusion

There are many good JavaScript frameworks and many more even better ones will come in the futures. A few years ago it was imaginable to develop a complex, large web application completely in JavaScript. Especially isomorph frameworks like React that are able to run on both client and server side completely dissolve this way of thinking. And as long as Google isn’t able to fully interpret JavaScript (or doesn’t want to) there is no other way than to render on the server and extend on the client.

This overview is supposed to show a few basics of React, yet there is a lot more to it. The next part will focus on server-side-rendering and communication.

Introduction to React.js: 1 Star2 Stars3 Stars4 Stars5 Stars 5.00 out of 5, 4 votes.
Loading ... Loading ...

About the Author

Roberto Bez is a passionate Webdeveloper and TechLead at HolidayCheck. For Roberto development is not only work or a job, but a great motivation and a new challange every day. Everything new and geeky, from new web-technologies to all kind of databases – he tries to introduce it in the daily development.