-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (46 loc) · 1.35 KB
/
index.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
57
58
59
// React.createElement
// React.createElement('div', {id: 'foo'}, 'foo') => {type: 'div', props: {id: 'foo', children: "foo"}}
function createTextElement(text){
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: []
}
};
}
function myCreateElement(type, props, ...children) {
return {
type,
props:{
...props,
children: children.map(child => {
return typeof child === 'object' ? child : createTextElement(child)
})
}
}
}
function myRender(element, container){
const dom = element.type == "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(element.type)
const isProp = key => key !== "children"
// for props other than children
Object.keys(element.props)
.filter(isProp)
.forEach(name => {
dom[name] = element.props[name]
})
element.props.children.forEach(child => myRender(child, dom));
container.appendChild(dom);
}
const AutoDidact = {
myCreateElement,
myRender
}
// ----------------------------------------------------------------------
const element = AutoDidact.myCreateElement('h1', {id: 'foo'}, 'Hello');
// Same
const container = document.getElementById('root');
// ReactDOM.render
AutoDidact.myRender(element, container);