Skip to content

Instantly share code, notes, and snippets.

@jahed

jahed/stub-react.js

Created Sep 28, 2018
Embed
What would you like to do?
Stub React
function ensureNodes(children) {
if (Array.isArray(children[0])) {
return ensureNodes(children[0])
}
return children
.filter(child => !!child)
.map(child => {
if (typeof child === 'string') {
return document.createTextNode(child);
}
return child
});
}
function createElement (tagNameOrComponent, props) {
props = props || {};
const children = ensureNodes(Array.prototype.slice.call(arguments, 2));
if (!tagNameOrComponent) {
return children;
}
if (typeof tagNameOrComponent === 'string') {
const tagName = tagNameOrComponent;
const element = document.createElement(tagName);
Object.keys(props)
.forEach(key => element.setAttribute(key, props[key]));
if (props.className) {
element.setAttribute('class', props.className);
}
children.forEach(child => {
element.appendChild(child);
});
return element
}
const Component = tagNameOrComponent;
return Component(Object.assign({}, props, { children: children }))
}
function render(element, container) {
if (Array.isArray(element)) {
element.forEach(e => container.appendChild(e));
return
}
container.appendChild(element)
}
const Fragment = props => createElement(undefined, {}, props.children);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment