May 2, 2014

React and CoffeeScript, with or without JSX

React, from Facebook, is a fascinating JavaScript library for programming in the reactive style that "uses a virtual DOM diff implementation for ultra-high performance." In order to understand the impact high-speed rendering can have on user experience, check out the Relato npm project statistics demo. I was blown away by how enjoyable it can be to navigate a huge dataset when the page transitions feel instantaneous. Wow!

One of the first things you'll notice when you look at the JavaScript examples on the React site is the usage of JSX, which is an embedded templating system that requires a special compiler.

Without JSX

You may not like the idea of markup in your JavaScript. And in fact, using CoffeeScript, you can write succinct, readable React code without using JSX, as demonstrated in the blog posts React, JSX, and CoffeeScript by Evan Martin and React & CoffeeScript by Vjeux. This Gist shows how to alias the properties of React.DOM in CoffeeScript.

There are even a couple of small projects that attempt to improve the experience of using React in CoffeeScript without JSX: react-coffee and react-kup.

A developer on a large-scale React project shared this experience:
Development of such a large project took 4 months and many sleepless nights.
In the beginning we used CoffeeScript, but after some time we tried JSX and it was amazing.
Great to hear that JSX works well, but is it really necessary to give up CoffeeScript in order to use it?

With JSX

One of the simplest solutions is to just use CoffeeScript's backtick escape syntax to "shell out" the JSX for subsequent compilation. This is demonstrated among other places in a comment on the still-open React GitHub issue for supporting languages like CoffeeScript.

Finally, in case you feel CoffeeScript deserves its own port of JSX, you're not (completely) alone. The coffee-react-transform project introduces "CSX" to let you "build React components in Coffeescript with JSX-like markup."

But no matter how you do it, give React a try with CoffeeScript!

No comments:

Post a Comment