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
.
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?