-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
56 lines (56 loc) · 1.92 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// React Implementation
//
const React = {
// this function will be called on the lowest level children first, then the parent, then the parent of the parent, and so on
createElement: (tag, props, ...children) => {
// Handle a ReactComponent function, so we can construct the virtual DOM
if (typeof tag === 'function') {
return tag(props, ...children);
}
return {
tag,
props,
children
};
}
};
const render = (element, container) => {
// handle edge cases like text nodes
if (!element.tag) {
// handle text nodes
if (typeof element === 'string') {
container.appendChild(document.createTextNode(element));
return;
}
}
// create the actual dom element from the virtual dom element
const domElement = document.createElement(element.tag);
// set props
const elementProps = element.props ? Object.keys(element.props) : [];
for (let i = 0; i < elementProps.length; i++) {
domElement[elementProps[i]] = element.props[elementProps[i]];
}
// create the children of the virtual dom element
if (element.children && Array.isArray(element.children)) {
for (let j = 0; j < element.children.length; j++) {
// render each child, the first element will be the container
render(element.children[j], domElement);
}
}
// append the dom node to the container
container.appendChild(domElement);
};
//
// The actual app
//
// Virtual DOM
// Wrap the "ReactElement" in a "ReactComponent" (function)
const App = () => {
const v = "A variable";
return (React.createElement("div", { draggable: true },
React.createElement("h2", null, "Hello React!"),
React.createElement("p", null, v),
React.createElement("input", { type: "text" })));
};
render(React.createElement(App, null), document.getElementById('root'));