Like React and JSX but also prefer CoffeeScript to JavaScript? Until recently, you were forced to write your React component renders by shelling out to JS with backticks or desugaring React.DOM to create lightweight DSL.

Luckily for us wanting the real deal, James Friend has created CoffeeScript transformer for JSX which allows you to write that nicely formatted JSX also in your .coffee files.

coffee-react-transform can be used through CLI or API. If you want CoffeeScript executable that understands CJSX, you can use coffee-react from the same author.

Requiring CJSXified .coffee files in node

If you want to use the vanilla coffee executable to require CJSX enhanced files, you can use node-cjsx module, which transparently compiles CJSX with coffee-react-transform before second compilation step with regular coffee binary. Just add require('node-cjsx').transform() to your app and you’re good to go.

Sublime Text

If you use Sublime Text, there’s a way to make working with CJSX much more enjoyable.

First, you can install sublime-react which just had CJSX support committed in by Tim Griesser. It provides syntax highlighting and autocompletion snippets for CJSX.

Second, you can change Better CoffeeScript plugin to use previously mentioned coffee-react as its coffee executable. Easy way to do that is to create symbolic link from your cjsx binary (e.g. ~/.nvm/v0.10.28/bin/cjsx) to ~/bin/coffee and setting ~/bin as "binDir" in CoffeeScript.sublime-settings. Also remember to change `“envPATH” in that same settings file to a directory containing node executable (e.g. ~/nvm/v0.10.28/bin).

NOTE: Replace ~ with your home dir, so e.g. ~/bin becomes /Users/hoppula/bin, Sublime does not seem to understand ~/ in config files.

Now you’ll get a nice preview of compiled JavaScript when you press ALT+SHIFT+D while editing your component’s .coffee file.

CJSX to JavaScript conversion example

CoffeeScript source
# @cjsx React.DOM
React = require 'react'

Team = React.createClass
  render: ->
    <div className="team">
      <div>{@props.team.name}</div>
      <div>{@props.team.city}</div>
    </div>

module.exports = Team
Compiled JavaScript
var React, Team;

React = require('react');

Team = React.createClass({
  render: function() {
    return React.DOM.div({
      "className": "team"
    }, React.DOM.div(null, this.props.team.name),
    React.DOM.div(null, this.props.team.city));
  }
});

module.exports = Team;

Browserify

James Friend has also written coffee-reactify browserify plugin, so you can easily use that same view code when rendering on server and in browser. I’ll write another blog post later on about developing isomorphic CoffeeScript apps with React and Exoskeleton.