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

Introduction to Reactive JavaScript with Facebook React

Have a look at React library developed by Facebook and Instagram, which presents a new paradigm for the development of web applications.

One of the presentations that caught my eye lately this year was to Stoyan Stefanov, author of the classic JavaScript Patterns. Stoyan showed React library (see Links section), developed by the Facebook/Instagram personnel.

Although not a very charismatic speaker, the code shown by Stoyan left me with a flea in the ear by having a syntax beyond weird and escape some of the most conservative approach adopted by libraries and market frameworks.

After trying a few quick applications, I was quite surprised and pleased with the result of using React.

Declarative JavaScript

React can be compared with the framework AngularJS, of Google, being declarative, that is, to make you, the developer, to focus more on results than on how it is achieved. In practice, this means that you will write some JavaScript code and get a working application in a very short time.

Another great advantage of React is that it works with a pseudo-DOM in memory. As you know (or should know), manipulate the DOM is one of the main causes of performance bottlenecks on websites and web apps and React solves this brilliantly working with a "DOM" itself.

Every time an element to be rendered, the library identifies the updates comparing the element in the DOM and memory by modifying only what was actually changed without rendering any element.

Reactive JavaScript

Another strength of the React library is to create reusable components. The idea of Web Components, e.g, is similar to React and make your own implementation.

Every component of React has two main attributes: state and properties (props). Whenever the state of a component is changed, it is rendered - this is reactive JavaScript. Furthermore, by re-render a component in React makes a comparison between the current state and the new state and renders only that has been modified, ie do not rerender all attributes and content of the element in the DOM.

JSX

A very strange part in the first contact with the React library is using the JSX syntax that transforms XML to JavaScript. In the examples you will see HTML markup (not string) in the middle of JavaScript code.

Importantly, the use of JSX is optional. It is also important to say that JSX can be used with any JavaScript code, not only React.

Take a simple example:

// JSX:
var Site,
    mrbool = <Site url="http://www.mrbool.com" name="MrBool" />;

Transforming it to JavaScript we have the following:

var mrbool = Site({url:"http://www.mrbool.br", name:"MrBool"});

Note that we need to have the Site object in the scope of the JSX, even it not being used. XML is converted to the call of this object where the attributes of the Site tag transform themselves to Site object properties.

The React website offers an online JSX compiler in case you want to play and experiment with the syntax (see Links section). The concept and implementation of the JSX are so interesting that would be worth an article itself.

Example of Application

After much theory, it's time to see React in practice. Let's start with the initial structure of our HTML:

<!doctype html>
<html>
    <head>
        <title>Shopping list ReactJS</title>
    </head>
    <body>
        <div id="container" class="container"></div>
        <script type="text/javascript" src="react.js"></script>
        <script type="text/javascript" src="JSXTransformer.js"></script>
    </body>
</html>

Well, that's all we write of HTML. In fact, we'll still write more HTML, but using the JSX format within our React code.

We will declare our script to type ("text/jsx") and comment (required) indicating that our code uses JSX syntax and it needs to be compiled in real time by JSX Transformer:

<script type="text/jsx">
/**
* @jsx React.DOM
*/
</script>

Of course you should not do this in production. The react offers one set of tools as a npm package that includes a command-line compiler to JSX. To install, type: npm install react-tools -g. Then, the jsx command becomes available and it can be used to compile and observe changes in JSX files. In our example, to facilitate, we will continue using JSX inline, compiled in real time. But, do not do this in production!

Continuing, we will create our first component, the container of our shopping list:

<script type="text/jsx">
/**
* @jsx React.DOM
*/
var ShoppingBox = React.createClass({
    render: function () {
        return (
            <div>
                <h1>My Shopping List</h1>
            </div>
        );
    }
});
 
React.renderComponent(
    <ShoppingBox />,
    document.getElementById('container')
);
</script>

Can you see this document.getElementById up there? Most likely this is the only time you interact with the DOM directly on a React app. We need to define the container element of our app. The rest of the operations will be made through the DOM in the Reactmemory.

Our first component does not do much, just add its markup. We will now add two new components: a table that lists the products on our list and the form to register a new product:

<script type="text/jsx">
/**
* @jsx React.DOM
*/
var ShoppingBox = React.createClass({
    render: function () {
        return (
            <div>
                <h1>My Shopping List</h1>
                <ShoppingTable />
                <ShoppingForm />
            </div>
        );
    }
});
 
var ShoppingTable = React.createClass({
    render: function () {
        return (
            <table>
                <thead>
                    <tr>
                        <th>Bought?</th>
                        <th>Product</th>
                        <th>Quantity</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        );
    }
});
 
var ShoppingForm = React.createClass({
    render: function () {
        return (
            <form>
                <input type="text" placeholder="Product" />
                <input type="number" placeholder="Quantity" />
                <button type="submit">Add Item</button>
            </form>
        );
    }
});
 
React.renderComponent(
    <ShoppingBox />,
    document.getElementById('container')
);

Now, in addition to container, we are also rendering the table and form. Our last component is a component for the product itself. Add the following code before the call React.renderComponent:

...
var Product = React.createClass({
    render: function () {
        return (
            <tr>
                <td><input type="checkbox" /></td>
                <td>Product Test</td>
                <td>1</td>
            </tr>
        );
    }
});
...

To the product be rendered, we need to add the component to the render method of the table:

...
var ShoppingTable = React.createClass({
    render: function () {
        return (
            <table>
                <thead>
                    <tr>
                        <th>Bought?</th>
                        <th>Product</th>
                        <th>Quantity</th>
                    </tr>
                </thead>
                <tbody>
                	<Product />
                </tbody>
            </table>
        );
    }
});

Time to explain a few things. For now we have all our components renderingHTMLwithoutnothingdynamic but the components themselves. The components are created through React.createClass method, which receives an object with the methods of the component. The render method is required in any React component and is responsible for the user interface.

A component can be rendered in the render method of another component or in a container in the DOM using the React.renderComponent method, which takes as a parameter the components and the element in the DOM that receive them.

Another important note: a component to be rendered within another component, must be within a valid HTML element. So our ShoppingBox has a <div> element that contains the ShoppingTable and ShoppingForm components.

Now we start to make our dynamic application using small steps. The first step is the loading of certain products. Let's look at the code below:

...
var ShoppingTable = React.createClass({
    render: function () {
        return (
            <table>
                <thead>
                    <tr>
                        <th>Bought?</th>
                        <th>Product</th>
                        <th>Quantity</th>
                    </tr>
                </thead>
                <tbody>
                    <Product ammount={2} checked={false}>Milk
                    <Product ammount={4} checked={true}>Cookie
                </tbody>
            </table>
        );
    }
});
...

In the component creation of our product table we are passing two products with their respective attributes. The syntax of the JSX allows you to pass two types of values for the properties: a string (in quotation marks) or a JavaScript value using keys. In the above example we are passing the amount as an integer and the checked as a boolean.

We now need to change the code of our product component to receive and render the product passed in the Table component, removing our test product that was fixed in the code:

...
var Product = React.createClass({
    getInitialState: function() {
        return {checked: this.props.checked || false};
    },
    toggle: function () {
        this.setState({checked: !this.state.checked});
    },
    render: function () {
        var checked = (this.state.checked ? 'checked' : '');
        return (
            <tr>
                <td><input type="checkbox" checked={checked} onClick={this.toggle} /></td>
                <td>{this.props.children}</td>
                <td>{this.props.ammount}</td>
            </tr>
        );
    }
});
...

The getInitialState method is standard for any React component. It should return the initial state of a component, their default values. In the case of our product component, we check whether it is marked or not.

We also implemented the toggle method, which select and deselect a checkbox and that, in a final implementation, should update this information on the server. Note that the toggle was associated with the click event of our checkbox in the component rendering.

In the render method we access those two main attributes we mentioned earlier: state and props. First, we check if the product is marked or not and then define their number and their name. The children attribute search any child node of the JSX element we use, in our case a simple text node with the product name. Can you understand the difference between props and state? The first is all passed viaparameterto the component object and the second is the object state, a property already defined previously.

And if we wanted to pursue our initial products of a query to the server, in an API that would return a JSON object with the products? This is also trivial to React. Let's change our code:

...
var PRODUCTS = [
    {ammount: 2, checked: false, name: "Milk"},
    {ammount: 4, checked: true, name: "Cookie"}
];
...
var ShoppingBox = React.createClass({
    render: function () {
        return (
            <div>
                <h1>My Shopping List</h1>
                <ShoppingTable data={this.props.data} />
                <ShoppingForm />
            </div>
        );
    }
});
...
var ShoppingTable = React.createClass({
    render: function () {
        var productNodes = this.props.data.map(function (product) {
            return <Product ammount={product.ammount} checked={product.checked}>{product.name}</Product>;
        });
        return (
            <table>
                <thead>
                    <tr>
                        <th>Bought?</th>
                        <th>Product</th>
                        <th>Quantity</th>
                    </tr>
                </thead>
                <tbody>
                    {productNodes}
                </tbody>
            </table>
        );
    }
});
...
React.renderComponent(
    <ShoppingBox data={PRODUCTS} />,
    document.getElementById('container')
);
...

In this new round of code, we changed the ShoppingBox component to receive a date attribute with the JSON of the products. This JSON is passed when we render the main component. In addition, we changed the render method of the product table to create each component product found in the JSON object, resulting in the local variable productNodes.

Now, finally, we will implement our form:

...
var ShoppingBox = React.createClass({
    handleProductSubmit: function(product) {
        var products = this.state.data;
        products.push(product);
        this.setState({data: products});
    },
    getInitialState: function() {
        return {data: []};
    },
    render: function () {
        return (
            <div>
                <h1>My Shopping List</h1>
                <ShoppingTable data={this.state.data} />
                <ShoppingForm onProductSubmit={this.handleProductSubmit} />
            </div>
        );
    }
});
...
var ShoppingForm = React.createClass({
    handleSubmit: function() {
        var name = this.refs.name.getDOMNode().value.trim(),
            ammount = this.refs.ammount.getDOMNode().value.trim() || 1;
        if (!name) {
            return false;
        }
        this.props.onProductSubmit({name: name, ammount: ammount});
        this.refs.name.getDOMNode().value = '';
        this.refs.ammount.getDOMNode().value = '';
        return false;
    },
    render: function () {
        return (
            <form class="form-inline" role="form" onSubmit={this.handleSubmit}>
                <div class="form-group">
                    <input type="text" placeholder="Product" ref="name" class="form-control" />
                </div>
                <div class="form-group">
                    <input type="number" placeholder="Quantity" ref="ammount" class="form-control" />
                </div>
                <button type="submit" class="btn btn-primary">Add Item</button>
            </form>
        );
    }
});
...

The shipping process is handled in two different components. The form of the component is sending the proper form, enabling the ProductSubmit event. Treatment of this event, in turn, is borne by the ShoppingBox element, the container of our list, responsible for updating their status and rendering our list again. It makes sense, right? Each component has a well-defined responsibility.

Conclusion

Despite being a relatively new library, React is already used in production by Facebook and Instagram. Problems such as semantic and SEO, common to this type of framework, are still present. However, if you will develop a web application, where we have no such concerns, React is a great bet as a tool.

Links

React official webpage: http://facebook.github.io/react/

React JSX compiler: http://facebook.github.io/react/jsx-compiler.html



Julio is a System analyst and enthusiast of Information Technology. He is currently a developer at iFactory Solutions company, working in the development of strategic systems, is also a JAVA instructor. He has knowledge and experi...

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