Skip to content

Instantly share code, notes, and snippets.

@intrnl

intrnl/jsx-static.js

Last active Oct 15, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.