Upcoming and OnDemand Webinars View full list

How to use Facebook’s React Library to Build UIs, Part 1

Chris Aquino

Facebook’s React library is a JavaScript library for building high performance User Interfaces. As they like to say, it’s the just “V” in MVC. Better yet, it’s not a framework. What that means is that React isn’t interested in how you handle your data, routing or business logic. The API is refreshingly compact and easy to learn. In the first part of this series of posts, you’ll learn how to use React for building a very simple component.

3…2…1…

The main thing you do with React is build UI components. Here’s an example of a component that counts down the seconds until my next birthday. I’ll break it down into steps to make it easier to see how it’s put together.

<!DOCTYPE html>
<html>
  <head>
    <script src="http://fb.me/react-0.10.0.js"></script>
  </head>
  <body>
    <div id="container"></div>
    <script>
      var ExampleApplication = React.createClass({
        render: function() {
          var elapsed = Math.round(this.props.elapsed  / 100);
          var seconds = elapsed / 10 + (elapsed % 10 ? '' : '.0' );
          var message = 'Hooray! Another year in ' + seconds + ' seconds.';
          return React.DOM.h1(null, message);
        }
      });
      var bday = new Date("April 18, 2015 08:12:00");
      setInterval(function() {
        React.renderComponent(
          ExampleApplication({elapsed: bday.getTime() - new Date().getTime()}),
          document.getElementById('container')
        );
      }, 50);
      </script>
  </body>
</html>

The main script consists of two main parts: creating a component and rendering the component. The setInterval is there just to make our countdown timer work.

Creating a component

To create a component, you call React.createClass. Note that this is a plain function call and not a call to a constructor. (Meaning you don’t have to worry about the new keyword.)

  var MyComponent = React.createClass({



  });

createClass takes one argument, an object literal. In the lingo of React, this object is the “spec” for your component. But your spec can’t be empty; you’re required to supply a single property: a render function.

  var MyComponent = React.createClass({
    render: function() {

    }

As you probably guessed, the render function of a component gets called when it needs to be drawn to the screen. But our component doesn’t draw anything. We’ll give it a return value that draws an H1 tag containing the text “Ni hao, React”:

  var MyComponent = React.createClass({
    render: function() {
      return React.DOM.h1(null, "Ni hao, React");
    }
  });

The return statement uses the value produced by the React.DOM.h1(...) call; there are functions in React.DOM corresponding to the other HTML tags as well. The first argument is for providing attributes to the h1, and the second argument specifies the textContent. In this example, we pass null as the first argument, meaning that we aren’t specifying any attributes.

Rendering a component

Rendering a component is as simple as:

  React.renderComponent(
    MyComponent(),
    document.getElementById('example')
  );

The React.renderComponent function takes two arguments. The first arugment is the result of invoking (or “calling”) a component function. The second is the DOM element to render your component to. Pretty simple, no?

You’ll notice a pattern emerging: React is all about functions. React uses a function (React.createClass) to create a component, which is just a function. Then, to render the component, you invoke the React.renderComponent function, and you pass it the result of invoking your component function.

Won’t this get tedious as we create more components? What if we want to use components inside of other components? Will we drown in function calls?

Fear not. They thought about this…

Using JSX to make using React easier

Instead of having to write:

var HelloMessage = React.createClass({
  render: function() {
    return (
      React.DOM.div(null,
        React.DOM.h1(null, "Greetings, Professor ", this.props.name,"."),
            React.DOM.p(null,
              "Would you like to play a game?",React.DOM.br(null ),
              "How about a nice game of",
              React.DOM.a( {href:"http://nsa.gov"}, "Chess"),"?"
            )
      )
    );
  }
});

React.renderComponent(HelloMessage( {name:"Professor Falken"} ), mountNode);

You’d probably rather write:

var HelloMessage = React.createClass({
  render: function() {
    return (
      <div>
        <h1>Greetings, Professor {this.props.name}.</h1>
            <p>
              Would you like to play a game?<br />
              How about a nice game of
              <a href="http://nsa.gov">Chess</a>?
            </p>
      </div>
    );
  }
});

React.renderComponent(<HelloMessage name="Professor Falken" />, mountNode);

I hear you saying, “Waitaminit. Is this PHP or something? Did you trick me?”
It’s not a trick. It’s JSX, which is just embedded XML in your JavaScript. This XML gets transformed into the corresponding React.DOM calls.

Though it’s not required, it makes using React easier on the eyes and has the added benefit of looking like the HTML that will be rendered to the screen.

To use JSX, you have two options. You can either pre-process your JavaScript code (more on this later), or you can include the following script tag:

    <script src="http://fb.me/JSXTransformer-0.10.0.js"></script>

You’ll really only want to use this for development because the XML transformation takes place in the browser, which adds extra overhead and can slow things down if you have a lot of components.

Including the JSXTransformer script will handle your JSX, but only if you modify your script tag a little. You’ve got to change the type and you have to add a comment at the top, like so:

<script type="text/jsx">
  /** @jsx React.DOM
  */
    var HelloMessage = React.createClass({
      render: function() {
        return (
          <div>
            <h1>Greetings, Professor {this.props.name}.</h1>
                <p>
                  Would you like to play a game?<br />
                  How about a nice game of
                  <a href="http://nsa.gov">Chess</a>?
                </p>
          </div>
        );
      }
    });

    React.renderComponent(<HelloMessage name="Professor Falken" />, mountNode);
</script>

The type="text/jsx" tells the browser that it’s not JavaScript, so it shouldn’t try to run it as-is. The comment /** @jsx React.DOM */ instructs the JSXTransformer to turn the XML into React.DOM function calls. These small modifications are a small price to pay for ease of reading.

What’s Next

With Facebook’s React library, it’s easy to create UI components for your web apps. In this post, we introduced the basics of creating a component with React.createClass, using JSX for quicker development and rendering a component with React.renderComponent. In an upcoming post, we’ll create a larger app that shows you how to compose a component hierarchy and create reactive data flows.

Want to know more? In the second post, Chris shows you how to use Facebook’s React library to create data flows between multiple components.

Not Happy with Your Current App, or Digital Product?

Submit your event

Let's Discuss Your Project

Let's Discuss Your Project