Running React.js JSX with CoffeeScript without any extra tools + JSFiddle Hello Worlds
02 Jun 2014Using CoffeeScript with React’s JSX
As a CoffeeScript lover, React’s JSX files are always bad to me. I tried lots of tools to make it run simply but never satisfied, the tools were not simple.
At last, I noticed that CoffeeScript has already a built-in feature to create JSX files easily, without an extra tool need. Even it says “you’ll never need to use it” in CoffeeScript’s documentation page, if you are working with React.js, it’s a cool and clean hack using Embedded JavaScript feature of CoffeeScript.
You can try the following fiddles:
Compiling on CLI
As I mentioned before, there is no extra tool needed. Just built-in React tools, and CoffeeScript compiler.
We created a coffee/
directory with a hello.coffee
in it. Let’s write our Hello
component:
And now, we should run this code:
After doing this, it will create jsx
and js
folders:
Let’s inspect the JS file which is generated by the command above:
It’s done! :)
Using with Rails Asset Pipeline
Also you can use this technique with Rails Asset Pipeline very easily. You can read official documentation.
After adding react-rails
gem, update bundles:
You can create a CoffeeScript file with the extension .jsx.coffee
and it will automatically compile to
JavaScript file. (Create app/assets/javascripts/hello.jsx.coffee
and test with the code above)
Don’t forget to add ###* @jsx React.DOM ###
beginning of the file.