JSX without React
Lately I've been playing around with A-Frame, a framework
that allows you to build VR experiences using HTML.
My goal was to represent a directory tree as a series of platforms connected by
paths, with spheres representing files.
This required creating and inserting DOM nodes for each directory or file, each
with a few dynamic attributes.
Doing that with vanilla javascript became pretty tedious. Here's an example:
AFRAME.registerComponent('insert-box', {init() {const newBox = document.createElement('a-box');newBox.setAttribute('position', { x: 0, y: 1, z: -3 });newBox.setAttribute('color', '#4CC3D9');newBox.setAttribute('rotation', { x: 0, y: 45, z: 0 });newBox.setAttribute('height', 1);newBox.setAttribute('width', 1);newBox.setAttribute('material', 'side: double;');const sceneEl = document.querySelector('a-scene');sceneEl.appendChild(newBox);}})
With JSX
I've mostly been
writing React lately and I've grown used to how easy JSX makes templating
templating.
That made me think, can I use JSX for this usecase, but without React?
A package called jsx-dom does exactly
that! Used as a Babel plugin, it transpiles JSX using
document.createElement
and element.setAttribute
, allowing you to easily write dynamic html within js.AFRAME.registerComponent('insert-box', {init() {const sceneEl = document.querySelector('a-scene');sceneEl.appendChild(<a-boxposition={{ x: 0, y: 1, z: -3 }}color="#4CC3D9"height={1}width={1}rotationmaterial={{ side: 'double' }}/>);}});
This approach isn't an attempt to use any of the features of React. It is just
some syntactic sugar for creating DOM nodes. But it makes my code a lot easier
to reason about!
Why am I doing this?
This is all part of an ongoing effort to develop a VR representation of code.
I'll be presenting my experiments at RubyConf Colombia on September 20th. I'll
also be writing more about my experiments as I go, so if that sounds
interesting, keep an eye out for more articles!