Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Component-based JavaScript Development with React.js

React takes a different approach than your run of the mill JavaScript framework on several fronts. Learn more about the unique features.


React.js Overview

React.js is an open source JavaScript framework from the developers at Facebook. React takes a different approach than your run of the mill JavaScript framework on several fronts. First of all, it focuses only on the view part of MVC frameworks. Most other popular frameworks, such as Backbone, Angular and Ember try to provide an all-inclusive solution to the problem of building web applications. It has garnered a lot of followers for a very good reason: It is awesome!

Another major difference is that with React you build your application as a set of autonomous components (that can be nested arbitrarily). React.js also employs some serious trickery to get super-fast performance. It renders the entire component tree from scratch every time to a virtual DOM and then, using a smart diff algorithm, it modifies the actual DOM only as necessary.

Finally, with React.js you often work with a special XML syntax called JSX, which is not required but makes things much easier to grasp and manage. I will use JSX in the examples here.

A Simple React.js Application

As any web application (although there is React native too) a React.js application is hosted on an HTML file. Here is a simple skeleton:

<html> <head> <title>Simple React.js skeleton</title> <script src="https://fb.me/react-0.13.1.js"></script> <script src="https://fb.me/JSXTransformer-0.13.1.js"></script> </head> <body> <div id="content"></div> <script type="text/jsx"> // ****** React.js code place holder ****** </script> </body> </html>

You can save this skeleton HTML file locally and load it in your browser. No need for a server. The skeleton includes links to React itself, as well as to the on-the-fly JSX transformer that translates the JSX syntax into JavaScript. This is very convenient for during development, but for production you should use a different setup, where you precompile the JSX.

Let's start with a simple example of a React component that displays some text on a color background. Beware: hideous colors and styles follow!

var ColorText = React.createClass({ render: function() { var style = { color: 'blue', backgroundColor: 'red', fontSize: 50 }; return <div style={style}>{this.props.text}</div > ; } }); React.render( < ColorText text = "Yeah, it works!!!" / > , document.getElementById('container'));

This is what it looks like:

Let's break it down piece by piece. You define a React component called ColorText by calling the React.createClass() function, passing it an object that has a render() function. The render() function returns some HTML/CSS/JavaScript. The HTML/CSS generated by the render() function includes this weird {this.props.text} expression. The props (properties) of a React component is data passed to the component every time it is rendered. This allows the same component to exhibit versatile behavior depending on what properties it gets. Note how inline styling is done. It is very similar to CSS, but there are some differences in the name of attributes due to the JavaScript syntax. For example the CSS "background-color" attribute is an invalid JavaScript identifier, so it becomes "backgroundColor".

React's Render.render() function renders a component into a particular place in the DOM. In this case our ColorText component with its "text" property set to "Yeah, it works!" is rendered into the DOM's "container" div. So, the components' properties (this.props) are populated for each render as attributes. Note, that here the properties are hard-coded, but they are often more dynamic based on the state of the application or, very often, external data retrieved from remote APIs.

For non-trivial applications, React components will be nested and the Render.render() call will just render the top level component that will include more sub-components and possibly regular HTML/CSS/JavaScript.

Composite Component

The power of React comes from composing and nesting multiple component together. We have our ColorText component. Here is a simple Image component:

var Image = React.createClass({ render: function() { var style = { padding: this.props.padding, width: 40, height: 40 }; return <img style={style} src={this.props.url} />; } });

Now, we can create a composite component that uses the Image and the ColorText as building blocks:

var IconText = React.createClass({ render: function() { var style = { padding: this.props.padding }; return <span> <Image url={this.props.image_url} padding={this.props.padding} /> <ColorText text={this.props.text} /> </span> ; } });

The IconText component has an image on the left (the icon) and text on the right. The image and text are the Image and ColorText components. You can see how the render() function of the composite IconText components puts them inside of a regular HTML span element. This is another example of the power of React/JSX — the easy mixing of React components and HTML elements. The way it works is that each HTML element has a corresponding built-in React component. At the JSX level they looks just like HTML elements. The properties can propagate from parent to component to its children. For example, the "padding" property passed to the IconText component is used for its own style as well as the "padding" property of the Image component.

To render the IconText component replace the Render.render() call with the following call:

React.render(<IconText text="Yeah, it works!!!" padding="5" image_url=green_bullet /> , document.getElementById('content'));


The IconText component is nice, but doesn't fully capture the power of React. Enter the IconTextList component. This component takes an array of items in which each item has a name and an image url and displays a vertical list of IconText components.

var IconTextList = React.createClass({ render: function() { var style = { backgroundColor: 'black' }; var items = this.props.items; var list = items.map(function(x) { return <li> <IconText text={x[0]} image_url={x[1]} padding='5' /> </li> }); return <ul style={style}>{list}</ul> ; } });

Here the render() function produces an HTML unordered list, where each item is an IconText component based the "items" property. The actual items can reflect an active user list, or inventory that gets updated frequently or anything else. The IconTextList component doesn't care. It will render whichever items you provide.

Here is an example with a fixed list of items:

The full source code can be found here: https://gist.github.com/the-gigi/2d110690dff3fedcb8ad.

Gigi Sayfan is the chief platform architect of VRVIU, a start-up developing cutting-edge hardware + software technology in the virtual reality space. Gigi has been developing software professionally for 21 years in domains as diverse as instant messaging, morphing, chip fabrication process control, embedded multi-media application for game consoles, brain-inspired machine learning, custom browser development, web services for 3D distributed game platform, IoT/sensors and most recently virtual reality. He has written production code every day in many programming languages such as C, C++, C#, Python, Java, Delphi, Javascript and even Cobol and PowerBuilder for operating systems such as Windows (3.11 through 7), Linux, Mac OSX, Lynx (embedded) and Sony Playstation. His technical expertise includes databases, low-level networking, distributed systems, unorthodox user interfaces and general software development life cycle.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date