Skip to content

Instantly share code, notes, and snippets.

@mikew
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikew/e737273e42ed704c6c54 to your computer and use it in GitHub Desktop.
Save mikew/e737273e42ed704c6c54 to your computer and use it in GitHub Desktop.
components = {}
addOne = (name, component) ->
components[name] = component
return
addMany = (obj) ->
addOne name, component for own name, component of obj
return
createFactory = (tagName) ->
(props, children...) ->
if typeof tagName is 'string'
{tagName, id, className, refName} = parseTagName tagName
if id?
props ?= {}
props.id ?= id
if className?
props ?= {}
if props.className?
props.className += " #{className}"
else
props.className = className
if refName?
props ?= {}
props.ref ?= refName
component = components[tagName] ? tagName
else
props ?= {}
component = tagName
#builder = components[tagName] ? tagName
React.createElement component, props, children...
parseTagName = (tagName) ->
[tagNameWithId, classNames...] = tagName.split '.'
[tagNameWithRef, id] = tagNameWithId.split '#'
[tagName, refName] = tagNameWithRef.split '%'
if classNames.length > 0
className = classNames.join ' '
if !tagName or tagName is ''
tagName = 'div'
{tagName, className, id, refName}
createElement = (tagName, props, children...) ->
createFactory(tagName)(props, children...)
Mixin = {
createElement
createFactory
e: createElement
}
module.exports = {
Mixin
createElement
createFactory
addOne
addMany
parseTagName
}

React is great. Coffeescript is great. JSX is good to but not what we're after.

Example:

ElementBuilder = require './react-element-builder'

HeaderComponent = React.createClass
  displayName: 'HeaderComponent'
  mixins: [ElementBuilder.Mixin]

  render: ->
    @e 'div#some-id.some-class', null, 'Hello world'

ElementBuilder.addMany { HeaderComponent }

AppComponent = React.createClass
  displayName: 'AppComponent'
  mixins: [ElementBuilder.Mixin]

  render: ->
    @e 'HeaderComponent'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment