Last active
October 15, 2020 10:06
-
-
Save intrnl/0635484c5f47907e55dd92cc7b6de372 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
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; | |
} |
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
/** @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