JSX: Writing the Language To Meet You

26 Jul 2024 - Ben

Like LISP, JSX allows html to be written “up” to easily define new concepts.

Like LISP macros, poorly written components and abstractions make them harder to work with. But well constructed ones make hard things easy to express.

Templating languages seem unable to allow the language to be written up to express harder concepts. But since JSX is an XML that closely mirrors HTML, where “tags” can be created and defined and expand into any amount of other tags, the markup language can be written up to the concepts they need to express. Making hard things easy to express, just like macros. Able to make hard things really hard to reason about, if done poorly, just like macros.

Almost like custom elements, although the compile-time vs run-time behavior still makes them a bit different enough that I don’t think custom elements would provide an useful implementation of this pattern. You can argue React/JSX is run time as well, but JSX has started to be found more places.

I got the inspiration from Lisp, but Elixir has good support for macros. I wish JavaScript had any type of macro system, instead of needing to bolt on code generation.

A good abstraction helps you understand the underlying technology, so remember you’re ultimately modelling HTML. Being able to use your abstraction layer while in the mindset of writing HTML is a good gauge on a good abstraction. A good example might be a modal or dialog, where the parent and child tags work together (like select/option or ul/li or table…):

<Modal.Root>
  <Modal.Trigger>
    Click Here!
  </Modal.Trigger>
  <Modal.Body>
    You are now looking at the content.  Click anywhere to close.
  </Modal.Body>
</Modal.Root>

Of course having a good mental model of HMTL helps yourself. But if you don’t start with one, you’ll learn as your write. Having a good goal to strive for is half the battle! Good luck on writing your React components.