Created
March 24, 2020 16:36
-
-
Save thaycacac/3f25409807abb4e6f6621c49a1d7ad1f to your computer and use it in GitHub Desktop.
build-your-react
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 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