Created
September 25, 2015 04:07
-
-
Save twfarland/fdcbd933bd876af79b33 to your computer and use it in GitHub Desktop.
React shorthand element creation
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
import React from 'react' | |
// E(String, { attr: val }, ... ReactElement || Atom) -> ReactElement | |
// Allows use of css selector shorthand and concise element creation | |
function E (head, attrs, ... child) { | |
if (typeof head === 'function') return React.createElement(head, attrs, ... child) | |
var i, p, c | |
const parts = head.split(/\s+/) | |
var tag = 'div' | |
var _attrs = {}, a | |
if (attrs) { | |
for (a in attrs) _attrs[a] = attrs[a]; | |
} | |
for (i = 0; i < parts.length; i++) { | |
p = parts[i] | |
c = p.charAt(0) | |
if (c === '#') { | |
_attrs.id = p.slice(1) | |
} else if (c === '.') { | |
_attrs.className = (!_attrs.className) ? p.slice(1) : _attrs.className + ' ' + p.slice(1) | |
} else { | |
tag = p | |
} | |
} | |
return React.createElement(tag, _attrs, ... child) | |
} | |
export default E |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment