A Quick Introduction to React

React is, according to their own definition, “A Javascript library for building user interfaces.” When I first read about react, it immediately struck me as a very good solution for a front end javascript framework. After making a couple small projects using react, I can conclude that it is a pretty great framework after all. In this post, I’ll outline how to hit the ground running as quickly as possible with react.

JSX — the syntax of React

React uses a specialized version of javascript called jsx. The basic idea is to provide some intuitive syntactic sugar to represent react’s internal version of the DOM which is used by react components — the building blocks of a react-based application. React’s official guide to jsx is quite comprehensive for learning the exact usage.

There are a few different ways to use jsx in your application, but at the end of the day jsx source code must eventually be converted to regular javascript. The first, and simplest, method is to simply include react’s JSXTransformer.js file, which provides a way to convert jsx-labeled javascript into plain old javascript.

The second way, which I prefer, is to precompile jsx source code beforehand. This is most easily done by taking advantage of react’s jsx command line tools:

$ npm install -g react-tools
$ cd project/
$ jsx --watch src/ build/

After doing this, using jsx is as simple as including build/whatever.js in your html file.

Getting up and running

After figuring out which jsx method you want to use, getting react working is trivial. Simply download react.js (or use a cdn) and include it in the head of your document:

<html>
    <head>
        <script src="react.js"></script>
        ...
    </head>
    <body>
        ...
        <script src="mine.js"></script>
    </body>
</html>

React doesn’t depend on any external libraries (such as jquery), so you don’t have to worry about that. However, make sure to include your source file after the content of your document.

Components — the building blocks of React

In react-land, Components are the central building blocks of your application. Components are self-contained, modular, dynamic representations of HTML in your application. Components are often children of other react Components. This makes more sense in context:

/** @jsx React.DOM */
var Thing = React.createClass({
  render: function() {
    return (
      <p>{this.props.name}</p>
    );
  }
});

var ThingList = React.createClass({
  render: function() {
    return (
      <h1>My Things:</h1>,
      <Thing name="Hello World!" />
    );
  }
});

React.renderComponent(
  <ThingList />,
  document.querySelector('body')
);

In this example, the renderComponent method kicks off the application by rendering a component into a given DOM node.

If this is your first time looking at React, a couple other things about this example should strike you as odd.

Is that HTML.. in my javascript?

No, not really. What you’re seeing is jsx in action, but the lines with HTML-like syntax do not represent actual DOM nodes. Instead, they are syntactic sugar for react’s internal representation of the DOM which also includes all components that you’ve previously declared. Code wrapped in curly braces is “escaped” from this syntax. Take a look at the precompiled version of the ThingList class:

var ThingList = React.createClass({displayName: 'ThingList',
  render: function() {
    return (
      React.DOM.h1(null, "My Things:"),
      Thing( {name:"Hello World!"} )
    );
  }
});

If this version makes more sense to you, that’s completely expected. When I first started using react, I has a strong distaste for the HTML-like syntax. However, as your components become progressively more complex, you may start to appreciate jsx syntax more than you thought. For example:

var ComplexThing = React.createClass({
  render: function() {
    return (
      <div className="complexThing">
        <Thing name="thing one" />
        <Thing name="thing two" />
      </div>,
      <a href="back.html">Go Back</a>
    );
  }
});

// In comparison, the non-jsx version:

var ComplexThing = React.createClass({displayName: 'ComplexThing',
  render: function() {
    return (
      React.DOM.div( {className:"complexThing"}, 
        Thing( {name:"thing one"} ),
        Thing( {name:"thing two"} )
      ),
      React.DOM.a( {href:"back.html"}, "Go Back")
    );
  }
});

Components and State

In my original example you may have noticed something strange — this.props.name. Where did props come from? What does it do?

Every react component takes in properties - immutable information specific to a particular instance of that component. You can think of this.props as the parameters that get passed into a function. However, because they are immutable, there’s no way to change the properties of a component after they are rendered. That’s where state comes in.

In addition to immutable properties, react components have a private this.state attribute. When a state gets updated, the component re-renders itself.

/** @jsx React.DOM */
var StatefulThing = React.createClass({
  updateName: function(event) {
    event.preventDefault();
    this.state.name = "Taylor";
  },
  setInitialState: function() {
    return (
      {name: "World"}
    );
  },
  render: function() {
    return (
      <a href="#" onClick={this.updateName}>
        My name is {this.state.name}
      </a>
    );
  }
});

React attaches event handlers to components using a camelCase naming convention, and expects you to pass it a function to handle the event.

One thing to keep in mind about all of the examples that we’ve seen is that none of them make any assumptions about other parts of your application. React is purely a front end development framework. In contrast to frameworks such as Backbone.js, React expects you to do the work of getting and pushing data from the server. This makes it very easy to implement React as a front end solution, since it simply expects you to hand it data. React does all the other work.

Hopefully this introduction gives you an idea of how react works. If you want to learn more about how to use react, I recommend reading their tutorial, which gives a broad overview of React’s features.

 
180
Kudos
 
180
Kudos

Read this next

A Better Development Workflow with Vagrant

In this post, I’d like to tell you about how I have abstracted almost everything away from my computer using just a couple tools: git and vagrant. So what’s so great about Vagrant? Anybody that knows me can tell you that I’m a neat freak... Continue →