Skip to content

Instantly share code, notes, and snippets.

@leontrolski
Created May 3, 2023 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leontrolski/b47e1918fe315d4ca1fa98c357137285 to your computer and use it in GitHub Desktop.
Save leontrolski/b47e1918fe315d4ca1fa98c357137285 to your computer and use it in GitHub Desktop.
Minimal frontend
<style>
.red {
color: red;
}
</style>
<div id="root"></div>
<script>
// Setup
const root = document.getElementById("root")
const make = (tag, attrs, ...children) => {
const el = document.createElement(tag)
if (attrs?.constructor !== Object){
throw `When calling make(...), make sure to pass in {attr: value, ...} as attrs, not: ${attrs}`
}
const classes = attrs.classes || []
delete attrs.classes
for (const c of classes){
el.classList.add(c)
}
for (const [k, v] of Object.entries(attrs)){
el[k] = v
}
el.replaceChildren(...children)
return el
}
// Our app
const state = {
count: 0,
}
const incCount = () => {
state.count = state.count + 1
render()
}
const button = () => {
return make(
"button",
{
onclick: incCount,
},
"increment count!"
)
}
const app = () => {
return make("div", {},
make("h1", {classes: ["red"]}, "Hello"),
button(),
make("p", {},
make("b", {}, `Count: ${state.count}`)
)
)
}
const render = () => {
root.replaceChildren(app())
}
render()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment