JSX for VanillaJS

Jack Herrington
2 min readOct 17, 2019

For a variety of reasons vanilla JS is getting some renewed interest. If you are thinking “Vanilla JS, ugh, another framework I haven’t heard of!” I feel your pain, but vanilla JS means just writing code without a framework.

For example, to create a new tag in vanilla JS you do something like this:

const newImage = document.createElement('img');
newImage.src = '/myimage.jpg';
document.getElementById('container').appendChild(newImage);

This creates a new image tag, sets its source URL and adds it to a container element, maybe a div or something.

If you would rather do this:

const '<img src="/myImage.jpg">';
document.getElementById('container').innerHTML = html;

That’s cool, and totally legit, but you should bail on this article because this article is about making it easy to create DOM nodes using JSX.

Alright, so you want to make DOM nodes, but making them gets to be a hassle after a while, particularly if they are nested. It’s a lot of code and lots of code means potentially lots of bugs. Plus, changing the nesting of tags become a big hassle.

Turns out, we can use JSX without react. And, even better, with just a little code we can use JSX to build DOM tags for us. Check out this example on Codepen.

Using JSX to build Vanilla JS DOM elements

Using JSX you can now create very complex DOM structures in a very readable format.

Would it be a pain in the butt to add a new tag in that system? Heck no!

There is no runtime overhead to this technique, once Babel has transpiled your code into vanilla JS you can look at it yourself to see that the code is simply making multiple nested calls to the DOM element creator function.

It’s probably slightly more efficient to hand craft the DOM element creation. But I’ll trade a little run time inefficiency for a more readable and maintainable code base.

--

--