Skip to content

Instantly share code, notes, and snippets.

@davidnormo
Last active August 29, 2015 14:26
Show Gist options
  • Save davidnormo/f9e09b95b65e98faf3b9 to your computer and use it in GitHub Desktop.
Save davidnormo/f9e09b95b65e98faf3b9 to your computer and use it in GitHub Desktop.
JSX Explored

JSX Explored

It is very common to see JSX and React together and you'd (almost) be forgiven for thinking they were part of the same library. That is, until you came to use React and found that you had to compile any JSX before being able to run your code.

JSX is completely separate to React. Take a look: https://facebook.github.io/jsx. JSX is an ECMAscript syntax extension specification. It is intended as a declarative, Domain Specific Language (DSL) that can be compiled to Javascript.

In essence, the React JSX transpiler takes this:

<MyComponent />;

and outputs this:

React.createElement(MyComponent);

Now, like I said, JSX is separate to React. You could transpile JSX to any valid JS. There are a number of parsers that implement the JSX extension. Or even some transpilers that allow you to configure the output JS from JSX. But if you are happy with the React API there's a third, simpler option.

Do you remember a little while ago this annotation syntax:

/** @jsx React */

This would be used before any JSX to give the parser a helping hand. Although this is no longer necessary in the React world, it turns out Babel still supports it as a method to bootstrap JSX for your own needs. Simply replace in your object identifier like so:

/** @jsx MyLib */

And hey presto! Our JSX component above will compile to:

MyLib.createElement(MyComponent);

You can easily transpile JSX into JS and leverage your own code in the implementation! The API for the createElement method is:

createElement(function Constructor[, object|null props[, array|null children]]);

What about regular HTML elements such as the humble div? How do they fit into this? The rule that Babel uses is: if the identifier begins with an uppercase letter it is taken to be a function constructor else it will pass a string of the identifier as the first parameter to createElement.

What use is this?

You may want to use JSX in a non-React application e.g. Backbone. You can get all the benefits of declarative code and easily incorporate it into your projects.

What applications can you think of?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment