Lusitos Tech Blog

What Is Jsx / TSX?

My head as a vector graphic

Anyone who has ever worked with React will know the file extension JSX (TSX for TypeScript) and the HTML-related syntax. But what lies under the hood?

Problem

Anyone who has ever worked with React will know the file extension JSX (TSX for TypeScript) and the HTML-related syntax.

Example:

const profile = (
  <div>
    <img src={u.avatar} className="profile" alt={`Pic of ${u.firstName}`} />
    <h3>{[u.firstName, u.lastName].join(" ")}</h3>
  </div>
);

But how does it work? This magic syntax is not supported by JavaScript itself.

Solution

A transpiler (e.g. babel or tsc) converts JSX/TSX into pure JavaScript code. The example shown above would be compiled to the following JS:

const profile = React.createElement(
  "div",
  null,
  React.createElement("img", { src: u.avatar, className: "profile", alt: `Pic of ${u.firstName}` }),
  React.createElement("h3", null, [u.firstName, u.lastName].join(" ")),
);
  • The function React.createElement gets as first parameter either a tag name or a component.
    • If the tag name in the JSX is lowercase, e.g.
  • The second parameter is an object with all properties assigned to the tag. If no properties have been assigned, this parameter is null.
  • The remaining parameters are the children that have been inserted into the tag.

Example

You can easily write a replacement for React which, instead of a Virtual DOM, creates real HTML elements with document.createElement:

function h(tag, props, ...children) {
  if (typeof tag === "function") return tag({ ...props, children });

  const element = document.createElement(tag);
  if (props) setAllAttributes(element, props);

  applyChildren(element, children);
  return element;
}

This function can be called instead of calling React.createElement. This very simple example even supports function components.

Further Aspects

This post was originally published here.