UI/UX Design

Why JSX is better than HTML Templating

In this post I will try to summarize my thoughts about why you should use JSX instead of HTML Templating.

What is JSX?

JSX was introduced in 2013 with React and is an XML-like syntax extension to ECMAScript without any defined semantics. It’s NOT intended to be implemented by engines or browsers. It’s NOT a proposal to incorporate JSX into the ECMAScript spec itself. It’s intended to be used by various preprocessors (transpilers) to transform these tokens into standard ECMAScript.

 

What is HTML Templating?

Templating refers to the client side method of binding data to views. Templating languages allow us to inject JavaScript directly into our HTML.

 

JSX Syntax

  
  
<Page index="1">
  <h1>About me</h1>
  <AboutMe content={aboutMeContent} />
</Page>;
  

 
transpiles to

  
  
React.createElement(
  Page,
  { "index": "1" },
  React.createElement("h1", null, "About me"),
  React.createElement(AboutMe, { content: aboutMeContent })
);
  

So as you can see in the example above, JSX is an HTML-like syntax for writing JavaScript related to the virtual DOM.

Under the hood, JSX is converted to a virtual DOM.

 

HTML Templating syntax

These are usually strings of HTML which are then fed to template engines like the ones from Vue.js or Angular.

  
  
<div class="page">
  <h1>{{aboutMeTitle}}</h1>
  <div>{{aboutMeContent}}</div>
</div>;
  

 
Under the hood, at design time, templates are just strings which are then converted to javascript which generates the virtual dom.

Which is better?

As you can see, templates have one more level of indirection, but the end result is the same. In terms of performance, I don’t think there is any difference between the 2.
Although templating languages do have advantages (like easier each loops and if/else blocks), they also tend to limit what you can write. By foregoing templates, JSX lets you take advantage of the expressiveness of JavaScript at any point in your code.This can admittedly result in code that’s harder to read and less approachable to non-programmers, compared to relatively straightforward templating syntaxes like Handlebars.

Adopting a pattern like the one that React is using (smart & dumb components and functional stateless components), you can bridge that gap and end up with components that are almost as easy to read as templates, while also being a lot more powerful.

Another benefit of JSX is that a team of designers can freely modify designs without worrying about breaking anything or even touching the logic.

The truth is, those who have a lot of JavaScript experience will tend to pick up JSX quite quickly. When I’m developing a component using React, it’s easier for me to picture the HTML generated when using JSX.

Andy

UI/UX Designer & Front-end Engineer based in Dublin currently working @IBM.
I write about: UI/UX Design, Javascript, HTML, CSS, React JS and React Native

1 comment