Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Created October 8, 2019 19:58
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 mikaelbr/476e0d1800f03977699e04355755ec00 to your computer and use it in GitHub Desktop.
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
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;
}
@iniatse
Copy link

iniatse commented Dec 3, 2020

Nice, but you made a mistake there. It should be

if (isEvent(k, val)) {

instead of

if (isEvent(k)) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment