Skip to content

Instantly share code, notes, and snippets.

@jahed
Created September 28, 2018 15:36
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 jahed/4fde815479c392a7175f338e2cec2337 to your computer and use it in GitHub Desktop.
Save jahed/4fde815479c392a7175f338e2cec2337 to your computer and use it in GitHub Desktop.
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