Skip to content

Instantly share code, notes, and snippets.

@koyanloshe
Forked from VanishMax/jsx-pragma.ts
Created April 9, 2023 07:02
Show Gist options
  • Save koyanloshe/3f254655e6baf62c14317d3be48d3907 to your computer and use it in GitHub Desktop.
Save koyanloshe/3f254655e6baf62c14317d3be48d3907 to your computer and use it in GitHub Desktop.
// Tag can be string or a function if we parse the functional component
type Tag = string | ((props: any, children: any[]) => JSX.Element);
// Attributes of the element – object or null
type Props = Record<string, string> | null;
// Element children – return value from the h()
type Children = (Node | string)[];
export const h = (tag: Tag, props: Props, ...children: Children) => {
// If tag is a component, call it
if (typeof tag === 'function') {
return tag({ ... props }, children);
}
// Create HTML-element with given attributes
const el = document.createElement(tag);
if (props) {
Object.entries(props).forEach(([key, val]) => {
if (key === 'className') {
el.classList.add(...(val as string || '').trim().split(' '));
return;
}
el.setAttribute(key, val);
});
}
// Append child elements into the parent
children.forEach((child) => {
el.append(child);
});
return el;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment