Introduction to JSX

JSX is a template language that is the recommended way to describe UI elements in React. This blog post will give you an introduction to what JSX is all about.

What is JSX?

JSX is technically XML. It is a pre-processor step that adds XML syntax to JavaScript. Here is an example:

class App extends Component {
  render() {
    return (
      <div className="App">
        <p>
          Hello Tom! <a href="http://kadwill.com">Here is a link to your website</a>.
        </p>
      </div>
    );
  }
}

Any lowercase node (div, p or a) is transpiled into HTML elements. JSX allows you to write as if you were in a normal HTML document.

Fundamentally, JSX just provides syntactic sugar for React.createElement(). Using Babel, you can see the JavaScript code, that the JSX code is transpiled into:

var App = function (_Component) {
  _createClass(App, [{
    key: "render",
    value: function render() {
      return React.createElement(
        "div",
        { className: "App" },
        React.createElement(
          "p",
          null,
          "Hello Tom! ",
          React.createElement(
            "a",
            { href: "http://kadwill.com" },
            "Here is a link to your website"
          ),
          "."
        )
      );
    }
  }]);

As you can see, it’s just a series of nested React.createElement() functions.

React components

If you give a node an uppercase name then it will be transpiled into a custom React component. For example, you could refactor the previous example by pulling some code out into a separate component. The code would look like this:

class Example extends Component {
  render() {
    return (
      <p>
        Hello Tom! You are writing React now! <a href="http://kadwill.com">Here is a link to your website</a>.
      </p>
    )
  }
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <Example />
      </div>
    );
  }
}

Thoughts

I’m new to React. My first thought was that JSX is a step backwards because it mixes template and view logic. I saw that as a negative because modern web development has been moving towards separating view and template logic. However, I can see that it provides a lot of control. It allows you to easily refactor a template by separating it out into multiple components.

I’m looking forward to playing with JSX more and seeing how it holds up in a large application.