Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code for blogpost "Using JSX for your own lightweight declarative library": https://medium.com/@mikaelbrevik/using-jsx-for-your-own-lightweight-declarative-library-a773d3796475
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
You can’t perform that action at this time.