Getting Started With JSX and HTML in JavaScript

For one of my personal projects, I found myself writing a lot of verbose vanilla javascript to create DOM elements, append text, add classes, attributes and event listeners — my code got really messy fast like this:

Image1: Creating HTML DOM nodes with classes, attributes, values etc in vanilla javascript.

It turns out incorporating HTML in your javascript code with JSX is quite simple.

What is JSX Anyways?

For those who don’t know about JSX, it’s code that looks like HTML that you write in your javascript code to create HTML elements.

Image2: A comparison of using JSX and plain javascript to create an HTML image element.

To use JSX you need to use a transpiler like babel in your project. If you haven’t used babel, I highly recommend you learn about it, as it powers so much of the modern javascript code that developers write today.

JSX vs Vanilla JavaScript

The previous image was simple, and some of you might still not see the value of using JSX over creating DOM elements in vanilla javascript. But as your codebase grows, complexity grows and having a tool like JSX to abstract things away can make ourlives as developers easier.

Image3: An example of DOM creation code, which I eventually swapped out for JSX.

Pros of JSX

  • it makes creating HTML elements in javascript easy
  • it makes your code much more readable and easier to reason about. In my original javascript code, I had to constantly picture what the resulting javascript code would look like
  • it saves you from thinking about the variable names for each DOM node you’re creating. “There are only two hard things in Computer Science: cache invalidation and naming things” — Phil Karlton
  • less technical folks can probably understand & modify the code
  • JSX compiles to the stuff you would have written anyways.

Cons of JSX

  • a build setup with transpiler is required

Use JSX Today — Here’s How

You can download very small example app created by opening your terminal and running these commands on your machine:

git clone
git checkout examples/simple-jsx
npm install
npm start

Find Me Elsewhere: Twitter, Github, Quora