jambit ToiletPaper #117

What is JSX / TSX?

Problem: File Extensions JSX / TSX in React / TypeScript

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?

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

Solution: Converting With a Transpiler

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 (function or class component).
    • If the tag name in the JSX is lowercase, e.g. <button>, the parameter is a string, otherwise (e.g. <Button>) it is a function or a class (which must be present in the scope with the same name).
  • 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.
What is JSX / TSX and how to convert it into pure JavaScript code

Cookie Settings

This website uses cookies to personalize content and ads, provide social media features, and analyze website traffic. In addition, information about your use of the website is shared with social media, advertising, and analytics partners. These partners may merge the information with other data that you have provided to them or that they have collected from you using the services.

For more information, please refer to our privacy policy. There you can also change your cookie settings later on.

contact icon

Contact us now