Skip to content

Instantly share code, notes, and snippets.

@toshsan
Last active September 16, 2018 18:07
Show Gist options
  • Save toshsan/b99f07692eb25a57ea4eb72078ee215b to your computer and use it in GitHub Desktop.
Save toshsan/b99f07692eb25a57ea4eb72078ee215b to your computer and use it in GitHub Desktop.
An experimental virtual dom/jsx renderer.
/** @jsx hype */
function render(root, el) {
while (root.lastChild) {
root.removeChild(root.lastChild);
}
root.appendChild(el);
}
function hype(name, attributes, ...children) {
if (typeof name === "function") {
return name(attributes, children);
}
var el = document.createElement(name);
for (var attr in attributes) {
if (attr.startsWith("on") && typeof attributes[attr] === "function") {
el.addEventListener(attr.substr(2).toLocaleLowerCase(), attributes[attr], false)
} else {
el[attr] = attributes[attr];
}
}
var node;
for (i = 0; i < children.length; i++) {
node = children[i];
if (typeof node === "function") {
el.appendChild(hype(node));
} else if (typeof node === "string") {
el.appendChild(document.createTextNode(node));
} else {
el.appendChild(node);
}
}
return el;
}
function soemthingclciked(e) {
console.log(e);
}
function Foo(props) {
return <div onClick={soemthingclciked}>{props.x}</div>;
}
function App() {
return <div onClick="hello">
<Foo x="1" />
<Foo x="2" />
</div>;
}
{
render(document.getElementById("root"), <App />);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="root"></div>
<script src="hype.js"></script>
</body>
</html>
@toshsan
Copy link
Author

toshsan commented Sep 16, 2018

Transpiled with buble: buble hype.jsx > hype.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment