Created
May 7, 2020 07:06
-
-
Save Akumzy/5429b199d4ff9c53be7dcf71d995108a to your computer and use it in GitHub Desktop.
HTML render function
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
<!DOCTYPE html> | |
<html lang="en"> | |
| |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
<style> | |
.card { | |
padding: 1rem; | |
border: 1px solid #ccc; | |
margin-bottom: 1rem; | |
} | |
</style> | |
</head> | |
| |
<body> | |
<div id="display"></div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> | |
<script> | |
window.onload = function () { | |
fetchData() | |
} | |
async function fetchData() { | |
try { | |
let response = await axios.get('https://randomuser.me/api/?results=100') | |
| |
/**@type {{results:{name:{first:string;last:string};email:string}[]}}}*/ | |
let data = response.data | |
| |
// Render the returned record | |
let frag = document.createDocumentFragment() | |
for (const user of users) { | |
frag.appendChild(userTemplate(user)) | |
} | |
// Insert the generated elements | |
display.appendChild(frag) | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
| |
/** | |
* Compose an template | |
* @param users {{name:{first:string;last:string};email:string}[]} | |
* */ | |
function userTemplate(users) { | |
return h( | |
'div', | |
{ | |
attr: { class: 'card' }, | |
}, | |
[ | |
h('h1', { | |
text: `${user.name.first} ${user.name.last}`, | |
}), | |
h('p', { | |
text: user.email, | |
}), | |
] | |
) | |
} | |
/** | |
* Create HTML Element | |
* | |
* @param tag {string} | |
* @param options {{text:string; attr:{[key:string]:string}}} | |
* @param children {HTMLElement[]} | |
* */ | |
function h(tag, options = {}, children) { | |
let el = document.createElement(tag) | |
for (const [name, value] of Object.entries(options)) { | |
switch (name) { | |
case 'attr': { | |
for (const [key, v] of Object.entries(value)) { | |
el.setAttribute(key, v) | |
} | |
| |
break | |
} | |
case 'text': | |
el.textContent = value | |
break | |
default: | |
break | |
} | |
} | |
if (Array.isArray(children)) { | |
children.forEach((e) => el.appendChild(e)) | |
} | |
return el | |
} | |
</script> | |
</body> | |
| |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment