Skip to content

Instantly share code, notes, and snippets.

@thaycacac
Created March 24, 2020 16:36
Show Gist options
  • Save thaycacac/3f25409807abb4e6f6621c49a1d7ad1f to your computer and use it in GitHub Desktop.
Save thaycacac/3f25409807abb4e6f6621c49a1d7ad1f to your computer and use it in GitHub Desktop.
build-your-react
function createElement(type, props, ...children) {
return {
type,
props: {
...props,
children: children.map(child =>
typeof child === "object" ? child : createTextElement(child)
)
}
};
}
function createTextElement(text) {
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: []
}
};
}
function render(element, container) {
const dom =
element.type == "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(element.type);
const isProperty = key => key !== "children";
Object.keys(element.props)
.filter(isProperty)
.forEach(name => {
dom[name] = element.props[name];
});
element.props.children.forEach(child => render(child, dom));
container.appendChild(dom);
}
const Didact = {
createElement,
render
};
/** @jsx Didact.createElement */
const element = (
<div style="background: salmon">
<h1>Hello World</h1>
<h2 style="text-align:right">from Didact</h2>
</div>
);
const container = document.getElementById("root");
Didact.render(element, container);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment