Can you use React without JSX?

Monday, Feb 2 2015 in react

That XML which appears to be mixed with JavaScript puts React newcomers off. This XML-like syntax is called JSX. Can you use React without JSX? You can, and it is easier than you imagine. I’ll show you how into this two-part series.

First, we need to make something clear: JSX is not XML. Before you deploy your React.js code, you usually use the react-tools package to transform the source into plain JavaScript. It should be now clear that you can use React without JSX, since you can just write the generated JavaScript by hand.

The question becomes: if I want to avoid JSX, is it practical to write the equivalent JavaScript by hand? I would say the answer is a qualified yes. Here is a minimal React component that just renders some static HTML:

var ExampleComponent = React.createClass({
  render: function () {
    return (
      <div className="example">
        <h1>Example Component</h1>
        <ul><li>One item</li><li>Another item</li></ul>
      </div>
    );
  }
});

It looks like HTML is somehow ‘embedded’ in JavaScript, but that’s all illusion. The JSX compiler will transform this into:

var ExampleComponent = React.createClass({displayName: "ExampleComponent",
  render: function () {
    return (
      React.createElement("div", {className: "example"},
        React.createElement("h1", null, "Example Component"),
        React.createElement("ul", null, React.createElement("li", null, "One item"),
          React.createElement("li", null, "Another item"))
      )
    );
  }
});

As you can see, JSX translates into calls to the React.createElement function. The first argument is a string or a function corresponding to the element that needs to be created, the second argument is an options object to configure the component (in this case we are setting the class attribute of the <div>), and the remaining arguments are the child elements. By nesting React.createElement calls, you can obtain the same effect as with JSX ‘tags’. JSX is there mainly to increase readability and reduce keystrokes.

In the next part, we’ll see how to make the JavaScript equivalent to JSX less verbose.