Skip to content

Instantly share code, notes, and snippets.

@whilelucky
Last active March 12, 2020 12:57
Show Gist options
  • Save whilelucky/6357be97894e195a7ef5f8f00aac81bd to your computer and use it in GitHub Desktop.
Save whilelucky/6357be97894e195a7ef5f8f00aac81bd to your computer and use it in GitHub Desktop.
const h = (type, props, ...children) =>
({ type, props, children });
/* -------------------- */
/* Creating */
/* -------------------- */
/* using h */
const App = (props) => h('div', null, 'hello');
/* -------------------- */
/* Aternative Creating */
/* -------------------- */
/* @babel/plugin-transform-react-jsx */
/** @jsx h */
const App = (props) => <div>hello</div>;
/* developit/htm :no build step needed: */
import htm from 'htm';
const html = htm.bind(h);
const App = (props) => html`<div>hello</div>`;
// better to use @babel/plugin-transform-react-jsx than babel-plugin-htm
/* -------------------- */
/* Rendering */
/* -------------------- */
const renderNode = (vNode) => {
let element;
if (vNode.split) {
return document.createTextNode(vNode);
}
element = document.createElement(vNode.type);
for (let key in vNode.props) {
element.setAttribute(key, vNode.props[key]);
}
(vNode.children || []).forEach((child) => {
element.appendChild(renderNode(child));
});
return element;
}
let currentApp;
const render = (state) => {
const vApp = App(state);
const newApp = renderNode(vApp);
currentApp
? document.body.replaceChild(newApp, currentApp);
: document.body.appendChild(newApp);
currentApp = newApp;
}
const state = { text: 'hello world' };
render(state);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment