Last active
July 7, 2017 19:48
-
-
Save theverything/131edddc0f325f14c1234506d5e2b7a7 to your computer and use it in GitHub Desktop.
React style create element function
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
function createElement(tag, props = {}, ...children) { | |
const element = document.createElement(tag); | |
const listeners = []; | |
Object.keys(props).forEach((key) => { | |
if (key.slice(0, 2) === 'on') { | |
const event = key.slice(2).toLowerCase(); | |
element.addEventListener(event, props[key]); | |
listeners.push(() => element.removeEventListener(event, props[key])); | |
} else if (key === 'ref' && typeof props[key] === 'function') { | |
props[key](element); | |
} else { | |
element[key] = props[key]; | |
} | |
}); | |
children.forEach((node) => { | |
if (node instanceof Node) { | |
element.appendChild(node); | |
if (node.destroy && typeof node.destroy === 'function') listeners.push(node.destroy); | |
} else { | |
element.appendChild(document.createTextNode(node)); | |
} | |
}); | |
element.destroy = () => listeners.forEach(removeEventListener => removeEventListener()); | |
return element; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment