web-dev-presentation/react.js
2023-11-07 21:25:24 -06:00

46 lines
981 B
JavaScript

let id = 1;
function createElement(type, props, ...children) {
const struct = {
id,
type,
props,
children: children.map((child) =>
typeof child === "object" ? child : { type: TEXT_NODE }
),
};
id += 1;
return struct;
}
function intoDom(virtEl) {
if (!virtEl) return null;
if (typeof virtEl === "string") return document.createTextNode(virtEl);
console.log("vi", virtEl);
if (typeof virtEl.type === "function") {
return intoDom(virtEl.type());
}
const el = virtEl.type
? document.createElement(virtEl.type)
: document.createDocumentFragment();
for (const c of virtEl.children ?? []) {
const domC = intoDom(c);
if (domC) el.appendChild(domC);
}
return el;
}
export function renderDom(domEl, virtEl) {
domEl.appendChild(intoDom(virtEl));
}
export function useState() {
let value;
const setter = (newValue) => {
value = newValue;
};
return [value, setter];
}
export default { createElement };