4 ms·
The author doesn’t do justice to hyperscript. Hyperscript’s one-to-one mapping with CSS selectors is great for readability while remaining terse. For example:
by jsf01 8y ago
The author doesn’t do justice to hyperscript. Hyperscript’s one-to-one mapping with CSS selectors is great for readability while remaining terse. For example:
let value = ‘example’;
let x = Math.random();
h(‘form.Foo[action=/whatever]’,
h(‘input.Bar[type=text]’, {
value,
oninput(event) {
value = event.target.value;
}
}),
h(‘button.button-small.button-primary[type=submit]’,
(x > 0.5) ?
h(‘strong’, ‘Submit’) :
h(‘em’, Submit)
)
)
vs.
let value = ‘example’;
let x = Math.random();
<form className=“Foo” action=“/whatever”>
<input
className=“Bar”
type=“text”
placeholder={}
value={value}
onInput={
(e) => value = e.target.value
}
/>
<button className=“button-small button-primary” type=“submit”>
{
(x > 0.5) ?
<strong>Submit</strong> :
<em>Submit</em>
}
</button>
</form>
Although the example is contrived, it highlights several of my pain points from when I used react/jsx.
The equivalent jsx requires transpilation, dipping back into js via {}, is far more verbose, and is particularly annoying when logic inevitably becomes part of your template. Whereas hyperscript style js solutions to view templating have straightforward access to loops, array methods, ternaries, objects, functions, etc. jsx requires you to either reinvent js functionality as components or switch back and forth between contexts to use js in your jsx template.
Hyperscript also nicely separates static vs dynamic properties in elements, making understanding a large code base easier. All the static stuff is in the selector, all dynamic stuff is in the optional second argument. There’s no equivalent in jsx.
As an aside, React’s hyperscript is kind of a pain to write on its own and there are many good reasons to stick with jsx if you’re using React. (Last I checked, React was strict about the second argument being an options object or null and the third argument being specifically an array of children.) My arguments in favor of hyperscript are most applicable if you’re using a library that was intended to be used with hyperscript, like Mithril or snabbdom.
- hombre_fatal 8y agoOne nice thing about JSX is the tooling/linting available for it. For example, tooling with warn when you have target=_blank without rel=noopener or whether you've defined the necessary attributes for each tag. It's one thing that got me using JSX years ago regardless of how I felt about JSX. Does the same level of tooling exists for hyperscript seeing that it's so much more string-based?