Show HN: A better way of writing HTML via JavaScript?
Although I've been using React for at least 5 years now, I don't quite like frameworks. For personal projects I sometimes use web component but they can be over kill depending on what you are trying to achieve. I do like JSX though. I think it's quite neat to be able to write HTML inside of JavaScript code. With that in mind, I've been trying to come up with a way to better create HTML dynamically.
Something along the lines of:
const req = await fetch('api.com/posts')
const data = await req.json()
for (const d of data)
createPost(d)
For that, I end up writing this piece of code const assignDeep = (elm, props) => Object.entries(props).forEach(([key, value]) =>
typeof value === 'object' ? assignDeep(elm[key], value) : Object.assign(elm, {[key]: value}))
const $c = (tag, props = {}, children = []) => {
const elm = document.createElement(tag)
assignDeep(elm, props)
elm.append(...children)
return elm
}
that way, I can define a blog post like this: const div = $c('div', {className: 'blog-post'}, [
$c('h1', {innerText: 'My blog post'}),
$c('div', {className: 'body'}, [
$c('p', {innerText: 'My first blog post'})
]),
$c('div', {className: 'footer'}, [
$c('span', {innerText: 'Author: '}, [
$c('a', {href: '#', innerText: 'atum47'})
]),
$c('span', {innerText: 'Date: ' + new Date().toLocaleString()})
])
]);
Here's an JS Fiddle of that code - https://jsfiddle.net/victorqribeiro/5cketz40/I think this is a simple and elegant way to create HTML elements in JavaScript reducing the verbose of calling document.createElement() and element.append() everywhere. What do you think?
10 comments
[ 1.9 ms ] story [ 16.3 ms ] threadI like your ideas! I think you should go deeper. Have you learned Racket and/or ANTLR before? This screams to me that you are the type of person that should be inventing languages! Come hang out here: https://reddit.com/r/programminglanguages
My user test: https://www.loom.com/share/ca86adff9abc4fb0ae294d32e491636a?...
https://lit.dev
I will repeat someone else's advice and recommend lit-html which is on its way to become part of the browser spec.
that would be a much better API.
Also, there is a very cool new JS framework called TiniJS: https://tinijs.dev/