React without JSX, part 2

In part 1, we have seen that JSX has a simple JavaScript equivalent and that you can use React with just plain JavaScript. Now, let’s make the code more concise.

React defines helper functions to create common HTML tags in the React.DOM namespace. For example, React.DOM.div, React.DOM.ul, and so on. These functions take a variable number of arguments. The configuration object is always the first argument and all the next arguments are the child elements.

For example, you can create a paragraph with

React.DOM.p({className: example}, 'Paragraph content');

As with React.createElement, you nest function calls to output nested HTML elements:

React.DOM.p({className: 'example'}, React.DOM.ul({id: 'items'}, React.DOM.li(null, 'Some text')));

Here is the same code with React.createElement and with JSX:

React.createElement('p', {className: 'example'},
   React.createElement('ul', {id: 'items'}. React.createElement('li', null, 'Some text)));
<p>
<ul id="items">
  <li>Some text</li>
</ul>
</p>

For components that you define, you can make your own helpers by calling React.createFactory on anything that is a valid first argument for React.createElement (in React 0.13, this will be either a string or a function; with React 0.12, it is either a string or whatever React.createClass returns).

var Component = function() {
  this.render = funnction() {
    return React.DOM.div({className: 'example'}, React.DOM.h1(null, 'title'});
  }
}

var Factory = React.createFactory(Component);

Factory(); // equivalent to React.createElement(Component);

Finally, nothing stops you from creating your own abstraction. One of the easiest ways is just to alias React.createElement to something shorter, like h:

var h = React.createElement

You end up with something really similar to existing JSX substitutes like JSnoX, but without an extra library. JSnoX does support CSS syntax for defining components, so if you are interested in even more concise code, you might want to take a look.