Telerik blogs
react_header

2015 is lining up to be the year of React. Lately, it has garnered a lot of attention, for front-end, mobile and server side JavaScript development. React seemed to pick up steam last year but its popularity is growing day after day, in part thanks to the success of the React.js Conf that took place in January. If all the buzz has made you curious about React, this article give you an overview of the library. We'll also discuss its strengths and why you might want to learn more about it.

What's React?

React is a JavaScript library created by a collaboration of Facebook and Instagram. Its aim is to allow developers to create fast user interfaces easily. React makes no assumptions about the rest of the technology stack used, thus it's easy to try it out on a small feature in an existing project.

It's currently adopted in production by big companies like Facebook, Instagram, Yahoo!, Airbnb, and Sony. As I said in the introduction its popularity is growing a lot, so I expect more companies to employ it very soon. In my opinion, the community hasn't been this excited about a JavaScript tool/library since the introduction of Node.js.

React isn't a complete framework. It doesn't offer all the components you’ll find in projects like Ember or AngularJS. In fact, many refer to React as just the V in MVC.

React Native

At the previously mentioned conference, the team behind React announced React Native. It can be used to create the UI of native mobile applications. React Native is slightly different from React because you don't create DOM nodes but real native elements. So you don't build JavaScript objects that are transformed into divs or spans but rather native elements like Image, Text or View.

Apart from this difference, they are based on the same principles and expose pretty much the same features, which is why the team introduced the idea of "Learn once, run everywhere". In this tutorial I won't cover React Native but I thought it was due a mention. If you're curious about this project you can watch these two videos recorded at the conference: video 1 and video 2.

Telerik offers a library called NativeScript that, similar to React Native, aims to let developers build native mobile apps with JavaScript. There are a number of differences between the projects, however. NativeScript is launching on March 5th. If you'd like to learn more about how NativeScript works, you can join us for a release webinar for an in-depth look at what the runtime can do.

Main aspects of React

Virtual DOM

One of most important and widely discussed concepts of React is the virtual DOM. The virtual DOM is a tree based on JavaScript objects created with React that mimics a DOM tree. Every time you want to change something in the DOM, React employs a diff algorithm that only re-renders the DOM nodes that have changed. This algorithm is used for efficient re-rendering because DOM operations are typically slow, at least compared to executing JavaScript statements. In this way, React can be very fast, which is especially important considering that the CPU of mobile devices are far less powerful than desktop devices.

Server-side Rendering

Another crucial feature of this project is that the objects you create with React, the views, can also be rendered on the server using Node.js. Unlike React Native, you don't have to use a different library. You employ the same file on the client as well as the server. This is an important performance improvement. In fact, you can first render a static version of the pages using the server, which is faster and also SEO-friendly, and then enable user interactions and UI updates by using React on the client-side.

Data-binding

The last feature I want to highlight is the data binding model used. Over the last few years, many frameworks, like AngularJS, have adopted a two-way data binding model. React is different because it has a one-way data-binding model. According to the React team, this model is easier to manage when developing an application.

Now that we've covered the main features of the framework, let's see how you can start using it.

Getting Started with React

To get started, you have two methods. The first is to use the Facebook CDN so that you don't have to download any files. Of course this method has the drawback that you must be online. The second method is to head over to the React website and download the React starter kit.

Once you have downloaded the zip, extract the files to your computer. You'll see a directory named "react-<version>" where <version> is the current version of the project. At the time of this writing the latest version is 0.12.2, in which case you'd have a folder named "react-0.12.2". Open the folder and then the "build" subfolder and you'll find the two files needed: JSXTransformer.js and react.js. The former lets you convert files containing code using the JSX syntax (adopted by most developers who use React) into files containing pure JavaScript statements. The second file is the core React library.

In the remainder of this tutorial, I'll use the Facebook CDN but you're free to adapt the snippets presented to use a local copy of the files. But before we build a first demo that employs React, it's important to discuss some important concepts.

Components

React pushes the idea of reusable components. They are widgets or other parts of a layout (a form, a button, or anything that can be marked up using HTML) that you can reuse multiple times in your web application. In React every component features a render() method which is responsible for displaying the HTML code. Usually React components are written using the JSX syntax, described in the following section, but you can use pure JavaScript as well.

The JSX syntax

JSX is a JavaScript syntax extension that looks similar to XML and that you mix with normal JavaScript code. Its use is optional but, as I said, most developers using React have employed it. It comes in handy because it's a concise syntax for defining tree structures with attributes. Being based on XML, it has the benefit of balanced open and closing tags. This can help make large trees easier to read than function calls or object literals. If you want to learn more about this syntax, you can read the article JSX in Depth.

Props and State

React relies on a unidirectional data flow. This means the data flow occurs from parent to child components via attributes. Inside the component you can access the values of the passed properties (or props using the React parlance), via the props object. When the values change, React makes sure to re-render your component so that your UI is up-to-date. In React, props are immutable which means that once passed, unless the parent is updated, they won't change.

In addition to props, every component can have its own, private data. This data is referred as state. A component can store a value in its state and pass it to its child components via props. This ensures that whenever a component’s state changes, the props also change. As a result the child components that depend on these props re-render themselves automatically.

Let's now put our React knowledge into action with a simple example.

Hello World with React

Now that you have a basic knowledge of the main concepts of React, it's time to see a concrete example. Let's start by creating a new index.html file containing the following code:

 

<html>
   <head>
      <title>Hello World with React</title>
   </head>
   <body>
      <script src="https://fb.me/react-0.12.2.js"></script>
      <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>
      <script type="text/jsx" src="hello.jsx"></script>
      <script type="text/jsx" src="main.jsx"></script>
   </body>
</html>

 

As you can see, in the code above we have four script elements. The first two files point to the two aforementioned files that enable us to use React. The third, hello.jsx, will contain our first React component. The last, main.jsx, will kick start the application by rendering our component.

The code below is our hello.jsx component:

 

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

 

In the above snippet, we've created a new React component by passing an object literal to the React.createClass() method, which implements the Factory pattern. The result of invoking this method is stored in a variable named Hello. Inside the object literal, we define a property called render which has a function as its value.

As I mentioned, render() is responsible for creating the objects that display the HTML code resulting from the component. However, instead of using a statement like console.log(), alert() or document.write(), we return the content to display. Here we're returning a paragraph with "Hello, world!".

We've built our first React component but on its own, this is not enough. We need to instruct the page to use our Hello component. We'll do that in the main.jsx file:

 

React.render(
   <Hello />,
   document.body
);

 

Although very short, this snippet gives us the chance to highlight a few concepts. The first is that, when we create a React component, it is like defining a new tag that we can use whenever we need it.

To use a component we need to invoke the React.render() method. This method takes two arguments: the component to render and the DOM element where we want to inject the result of the component. In our example, we want to render the Hello component and inject the content in the body of the document.

This example didn't use any props, but we'll look at this in the next example.

Using props in React

In this example, we'll update the previous code to see props in action. Instead of having a fixed message, hard-coded in the component, it'll be passed as an attribute. To do so, we have two update two snippets from the previous section.

The new hello.jsx will be:

 

var Hello = React.createClass({
   render: function() {
      return <p>{this.props.message}</p>;
   }
});

 

And the new main.jsx file will be:

 

React.render(
   <Hello message="Hello, world!" />,
   document.body
);

 

As you can see, we're passing the string through a message attribute added to the Hello tag in the main.jsx file. The passed value is retrieved by accessing the namesake property of the props object in the render() method of the Hello component. The result of this second example is the same as before, however, thanks to this change, our Hellocomponent is more reusable.

Conclusions

This article provided a brief overview of React, its main concepts, and JSX. At the beginning of the article we discussed how React can improve the performance of a website and how it allows you to create more SEO-friendly web pages. We covered props and state and how they can used to create more reusable components. Finally, we covered a couple of simple examples that use React.

As we've discussed, React has many benefits and it's probably the future of web development. I hope you enjoyed the article and will give React a try in your next project.

Header background via "Cocktail straws" by Dave Gough (spacepleb) - Licensed under CC BY 2.0 via Wikimedia Commons


Telerik Blogging Ninja
About the Author

Aurelio De Rosa

Aurelio is a (full-stack) web and app developer with more than 5 years experience programming for the web using HTML5, CSS3, JavaScript and PHP. His interests also include web security, web accessibility, SEO and WordPress. He's the author of the books jQuery in Action and Instant jQuery Selectors. You can find him on GitHub here.

Related Posts

Comments

Comments are disabled in preview mode.