-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (63 loc) · 1.85 KB
/
index.js
File metadata and controls
72 lines (63 loc) · 1.85 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Writing React code in plain JS
* Creating components with JSX
*/
// A stateless functional component
const Person = ({ name, phone, email }) => {
return React.createElement("div", { class: "contact" }, [
React.createElement("h2", {}, name),
React.createElement("div", { class: "details" }, [
React.createElement("p", {}, "Phone: " + phone),
React.createElement("p", {}, "Email: " + email),
]),
]);
};
// A Stateful functional component
const App = () => {
const [contacts, setContacts] = React.useState([]);
React.useEffect(() => {
(async () => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users`
);
if (response.status !== 200) {
//invoke handler
return;
}
const users = await response.json();
setContacts(users);
})();
}, []);
/*
* createElement takes in 3 args
1. component - A String or a Component
2. props object for the component passed in as arg1- {}
3. children
*/
return React.createElement("div", { class: "app" }, [
React.createElement("div", { class: "title-container" }, [
React.createElement("h1", { class: "title" }, "Contacts"),
]),
React.createElement("div", { class: "contacts-container" }, [
contacts.map((user) =>
React.createElement(
Person,
{ key: user.id, ...user },
null /* Optional argument */
)
),
]),
]);
/**
* So to answer the question, why JSX?
*
* As we can see, encapulating the underlying javascript code with JSX
* + improves the developer experience
* + code readablility
* by a large extent
*/
};
// Rendering to DOM with React-DOM
const container = document.getElementById("root");
const root = ReactDOM.createRoot(container);
root.render(React.createElement(App));