Skip to content

Instantly share code, notes, and snippets.

@jollytoad
Last active February 3, 2017 03:20
Show Gist options
  • Save jollytoad/18e0b3c5cfda26d22bb4 to your computer and use it in GitHub Desktop.
Save jollytoad/18e0b3c5cfda26d22bb4 to your computer and use it in GitHub Desktop.
Wrapper for virtual-dom/h to support compiled JSX (ES6)
import h from 'virtual-dom/h'
export default function(tag, props, ...children) {
if (typeof tag === 'function') {
return tag(props, ...children)
} else {
return h(tag, transformProps(props), children)
}
}
// Add attribute -> property mapping in here if you want any
const attrMap = {
"class": "className"
}
function transformProps(props) {
if (props) {
Object.getOwnPropertyNames(props).forEach(key => {
const sub = attrMap[key]
if (sub) {
// Apply any attribute to property mappings
props[sub] = props[key]
delete props[key]
} else if (key.startsWith("data-")) {
// Move any data- attributes into the dataset property
props.dataset = props.dataset || {}
props.dataset[dataKey(key)] = props[key]
delete props[key]
} else if (key.indexOf("-") !== -1) {
// Move any other attrs contains a '-' into attributes property
props.attributes = props.attributes || {}
props.attributes[key] = props[key]
delete props[key]
}
})
}
return props
}
function dataKey(input) {
return input.toLowerCase().replace(/^data-/,'').replace(/-(.)/g, (m, a) => a.toUpperCase())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment