Created
October 8, 2019 19:58
-
-
Save mikaelbr/476e0d1800f03977699e04355755ec00 to your computer and use it in GitHub Desktop.
Code for blogpost "Using JSX for your own lightweight declarative library": https://medium.com/@mikaelbrevik/using-jsx-for-your-own-lightweight-declarative-library-a773d3796475
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
const isEvent = (k, v) => k.startsWith("on") && typeof v === "function"; | |
const eventName = k => k.substr(2).toLowerCase(); | |
const isString = s => typeof s === "string"; | |
function attrs(el, props) { | |
// Remember, JSX sets props to `null` if nothing is defined, so in that case, we just return unchanged el | |
if (!props) { | |
return el; | |
} | |
// For every passed prop, we get key and value | |
for (let [k, val] of Object.entries(props)) { | |
// If it is an event, we add an event listener. | |
if (isEvent(k)) { | |
el.addEventListener(eventName(k), val); | |
} | |
// If the key is class, we use classList to add one or many CSS classes | |
else if (k === "class") { | |
const classes = Array.isArray(val) ? val : [val]; | |
el.classList.add(...classes); | |
} | |
// And finally, if neither class nor event, we set attribute using the setAttribute function. | |
else { | |
el.setAttribute(k, val); | |
} | |
} | |
return el; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, but you made a mistake there. It should be
instead of