redbadger/react-isomorphic

Proposed interface for `React.create-element` in LiveScript

Opened this issue ยท 4 comments

Since you don't use JSX in your LiveScript components (and aren't using jQuery, so $ is available), I thought I'd share this improved interface I use for React.create-element:

window.$ = (element, props-or-children, children-if-props) ->
  if (props-or-children? and props-or-children instanceof Array) or not (props-or-children instanceof Object)
    props = null
    children = props-or-children
  else
    props = props-or-children
    children = children-if-props
  React.create-element element, props, children

Object.keys(React.DOM).forEach (element-name) !->
  window."$#element-name" = (props, children) ->
    $ element-name, props, children

This allows me to build components in my render method like this:

$ Jumbotron, style: styles.welcome.base, [
  $h2 'this is a catchy tagline'
  $p 'here is a short mission statement, expanding on the tagline'
  $hr!
  $a href: '/demo', do
    $ Button,
      bs-style: \primary
      bs-size: \large
      'Try the demo'
]

A few significant advantages here:

  • I don't have to declare which React.DOM elements I'm using in each component, but I also don't have a bunch of single character functions such as a, i, p, etc cluttering my global scope.
  • I never have to write out the lengthy React.create-element.
  • It feels very functional, as $dom-element acts as a partial application of $ (i.e. $p ... is the same as $ 'p', ...).
  • Props are now optional for every component, so you'll never have to write, $ MyComponent, null or $ MyComponent, null, 'contents or children'. You can just write $ MyComponent and $ MyComponent, 'contents or children' respectively.

Thoughts?

I'd love to hear what others think about this, especially if you notice/anticipate any problems with it. It's great to see other LiveScripters using React! ๐Ÿ˜ƒ

Looks great! We came up with something very similar for Arch, have a look at https://github.com/arch-js/arch/blob/master/src/dom.ls. It's all written and meant to be used with LiveScript, btw :)

I like it! As a (relative) newcomer to LiveScript, it's great to see examples in the wild with a more functional style, which I'm still slowly adapting myself to. ๐Ÿ˜ƒ I'll be keeping my eye on Arch!

That's help ! :)

That's a great solution. I am researching to use React but want to get rid of the JSX hell lately.

However I think '_' is a better choice over '$' for a few reasons:

  • '_' is visually much cleaner
  • we don't need underscore for we have preludels
  • though lesser, personally I still use jQuery occasionally.