Created
April 7, 2022 06:40
-
-
Save VanishMax/3721a4b7252f9441005ee83b9652b2fa to your computer and use it in GitHub Desktop.
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
// 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