Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active October 15, 2020 10:06
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 intrnl/0635484c5f47907e55dd92cc7b6de372 to your computer and use it in GitHub Desktop.
Save intrnl/0635484c5f47907e55dd92cc7b6de372 to your computer and use it in GitHub Desktop.
function __append (el, children) {
for (let child of children) {
if (!child) continue;
if (Array.isArray(child)) __append(el, child);
else if (child instanceof HTMLElement || child instanceof DocumentFragment) el.append(child);
else el.append(document.createTextNode(child));
}
}
export function render (el, root) {
__append(root, [el]);
}
export function h (type, props, ...children) {
props = props || {};
children = props.children || children;
if (typeof type == 'function') {
props = { children, ...props };
return type(props);
}
let el = document.createElement(type);
let { children: _, ref, ...restProps } = props;
if (ref) ref.$ = el;
for (let prop in restProps) {
let val = restProps[prop];
if (prop == 'style') {
if (typeof val == 'string') {
el.setAttribute(prop, val);
} else {
for (let k in val) {
let v = val[k];
el.style[k] = typeof v != 'number' ? v : v + 'px';
}
}
continue;
}
el[prop] = val;
}
__append(el, children);
return el;
}
export function Fragment ({ children }) {
return children;
}
/** @jsx h */
/** @jsxFrag Fragment */
import { h, Fragment, render } from './jsx-static.js';
function Todo ({ content }) {
let todoRef = {};
return (
<li ref={todoRef}>
<div>{content}</div>
<button onclick={() => todoRef.$.remove()}>x</button>
</li>
)
}
function App () {
let listRef = {};
let inputRef = {};
return (
<Fragment>
<h1>Todos</h1>
<ol ref={listRef}></ol>
<input type='text' ref={inputRef} />
<button onclick={addTodo}>add</button>
</Fragment>
);
function addTodo () {
render(<Todo content={inputRef.$.value} />, listRef.$);
inputRef.$.value = '';
}
}
render(<App />, document.querySelector('#root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment