Last active
January 4, 2016 00:08
-
-
Save Flamefork/8539366 to your computer and use it in GitHub Desktop.
React addon for easier React.DOM building without JSX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// React addon for easier React.DOM building without JSX | |
// | |
// Usage: | |
// | |
// render: function () { | |
// return React.addons.tagHelper( | |
// ['#main.container', | |
// ['h1', 'Hello!'], | |
// ['a.andClass.andAnother', { href: '/' }, 'Home']] | |
// ); | |
// } | |
// | |
// | |
React.addons.tagHelper = (function () { | |
'use strict'; | |
function parseSpec(specString) { | |
if (!parseSpec.cache[specString]) { | |
var spec = specString.match(parseSpec.matcher); | |
parseSpec.cache[specString] = { | |
tag: spec[1] || 'div', | |
id: spec[3], | |
className: (spec[4] || '').replace(/\./gim, ' ').substr(1) | |
}; | |
} | |
return parseSpec.cache[specString]; | |
} | |
parseSpec.matcher = /([^#\.]+)?(#([^#\.]+))?((\.[^#\.]+)+)?/; | |
parseSpec.cache = {}; | |
function buildTag(tag, props, children) { | |
children.unshift(props); | |
return React.DOM[tag].apply(React.DOM, children); | |
} | |
function mergeSpecToProps(spec, props) { | |
if (props.className && props.className.constructor === Object) { | |
props.className = React.addons.classSet(props.className); | |
} | |
if (spec.className) { | |
props.className = spec.className + (props.className ? ' ' + props.className : ''); | |
} | |
props.id = props.id || spec.id; | |
} | |
function getChildren(arr, offset) { | |
var children = Array(arr.length - offset); | |
for (var i = offset; i < arr.length; i++) { | |
var child = arr[i]; | |
if (child && child.constructor === Array && typeof child[0] === 'string') { | |
child = React.addons.tagHelper(child); | |
} | |
children[i - offset] = child; | |
} | |
return children; | |
} | |
return function (params) { | |
var childrenOffset = 1; | |
var spec = parseSpec(params[0]); | |
var props = {}; | |
if (params[1] && params[1].constructor === Object) { | |
props = params[1]; | |
childrenOffset = 2; | |
} | |
mergeSpecToProps(spec, props); | |
var children = getChildren(params, childrenOffset); | |
return buildTag(spec.tag, props, children); | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment