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

Wir verwenden Cookies, um unsere Webseite für Sie zu optimieren. Mit dem Besuch unserer Webseite erklären Sie sich damit einverstanden. // Our website is using cookies to improve your experience. By continuing to browse the site, you are agreeing to our use of cookies.

Weitere Informationen finden Sie in unserer Datenschutzerklärung. // For more information, please refer to our privacy policy.