fka blog journal of programming studies

Running React.js JSX with CoffeeScript without any extra tools + JSFiddle Hello Worlds

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

    npm i -g coffee-script react-tools
    mkdir coffee
    touch coffee/hello.coffee

We created a coffee/ directory with a hello.coffee in it. Let’s write our Hello component:

###* @jsx React.DOM ###

Hello = React.createClass
  render: ->
    `<div>{this.props.name}</div>`

React.renderComponent `<Hello name="world" />`, document.body

And now, we should run this code:

coffee -c --no-header -o jsx/ coffee/ && jsx jsx/ js/

After doing this, it will create jsx and js folders:

$ ls
coffee js jsx

Let’s inspect the JS file which is generated by the command above:

(function() {
  var Hello;

  Hello = React.createClass({displayName: 'Hello',
    render: function() {
      return React.DOM.div(null, this.props.name);
    }
  });

  React.renderComponent(Hello( {name:"fatih"} ), document.getElementById('hello'));

}).call(this);

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.

# Coffee
gem 'coffee-rails'

# React
gem 'react-rails'

After adding react-rails gem, update bundles:

bundle install

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.