Created
September 28, 2018 15:36
-
-
Save jahed/4fde815479c392a7175f338e2cec2337 to your computer and use it in GitHub Desktop.
Stub React
This file contains hidden or 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
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