JSX: Markup Expressions in JavaScript, and What They Compile To
Read and write JSX confidently: elements as expressions, attributes and children, embedding JavaScript in braces, conditional rendering with && and ternaries, lists and keys, spread attributes, fragments, components and props, and how compilers turn JSX into function calls that build plain objects.
kvi5hnuCode Sprout team member6 min readOn this page
JSX is an extension to JavaScript syntax that lets you write tree-shaped data, usually user interfaces, with HTML-like tags inside JavaScript code. It was created for React, and it's also used by Preact, Solid, Qwik and others. JSX isn't JavaScript: browsers and Node can't run it, so a compiler (esbuild, Babel, SWC or TypeScript, article 136) turns every JSX expression into ordinary function calls. Once you know that rule, JSX holds few surprises. This article is about the syntax, with only as much React as needed for context.

Elements are expressions
A JSX element is an expression, like a string or regular expression literal, so it can be assigned, returned, passed as an argument or stored in an array:
const rule = <hr />;
const logo = <img src="logo.png" alt="Company logo" />;
const sidebar = (
<aside className="sidebar">
<h1>Menu</h1>
<p>Pick a section</p>
</aside>
);
The classic transform compiles each element into a call to React.createElement(type, props, ...children):
const rule = React.createElement("hr", null);
const sidebar = React.createElement("aside", { className: "sidebar" },
React.createElement("h1", null, "Menu"),
React.createElement("p", null, "Pick a section"));
Attributes become properties of the props object, and children become the remaining arguments. Parentheses around multi-line JSX aren't required, but they avoid automatic semicolon insertion after return (article 6). Differences from HTML follow from being JavaScript: class is a reserved word, so React uses className; for becomes htmlFor; attribute names are camelCase (onClick, tabIndex) except data-* and aria-*; every element must be closed (<br />); and a JSX expression must have one root element.
JavaScript inside braces
Inside JSX, curly braces switch back to JavaScript: any expression can be an attribute value or a child.
function Card({ title, items, showFooter, onPick }) {
return (
<section className="card" aria-label={title}>
<h2>{title.toUpperCase()}</h2>
<ul>
{items.map((item) => (
<li key={item.id} onClick={() => onPick(item.id)}>
{item.name}
</li>
))}
</ul>
{showFooter && <footer>{items.length} items</footer>}
</section>
);
}
Common patterns, all just JavaScript expressions:
- Conditional rendering:
{showFooter && <footer>...</footer>}uses short-circuiting (article 34). When the condition isfalse, the child isfalse, which renderers skip. For either/or, use a ternary:{loggedIn ? <Logout /> : <Login />}. Beware{count && <Badge />}: whencountis0, React renders the0. Write{count > 0 && <Badge />}. - Lists:
{items.map((item) => <li key={item.id}>...</li>)}produces an array of elements, which renderers flatten. Each item needs a stable, uniquekeyso React can match items between renders. Use IDs, not array indexes, when items can be reordered. A classic slip, common even in published examples, is writing themapcallback with braces but noreturn:items.map((item) => { <li>{item}</li> })returnsundefinedfor every item. - Objects as values:
style={{ padding: 10, color: "teal" }}, with outer braces for "JavaScript here" and inner braces for the object literal. - Functions as values:
onClick={() => onPick(item.id)}passes a function; don't call it there (onClick={onPick(item.id)}would run it during rendering). - Spread attributes:
<input {...commonProps} type="email" />copies all properties of an object into props, like object spread (article 52); later attributes override earlier ones. - Comments go inside braces:
{/* note */}.
Text in JSX is escaped automatically: a string containing <script> is rendered as text, not markup, which protects against injection (article 110). React's escape hatch for raw HTML is deliberately named dangerouslySetInnerHTML.
The modern transform
React 17 introduced the automatic runtime, which modern tools use by default. Instead of React.createElement, the compiler imports helper functions, and children move into props. Compiling the Card example with esbuild --jsx=automatic gives (formatted by Prettier):
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function Card({ title, items, showFooter, onPick }) {
return /* @__PURE__ */ jsxs("section", {
className: "card",
"aria-label": title,
children: [
/* @__PURE__ */ jsx("h2", { children: title.toUpperCase() }),
/* @__PURE__ */ jsx("ul", {
children: items.map((item) =>
/* @__PURE__ */ jsx(
"li",
{ onClick: () => onPick(item.id), children: item.name },
item.id,
),
),
}),
showFooter &&
/* @__PURE__ */ jsxs("footer", { children: [items.length, " items"] }),
],
});
}
Notice that key is passed separately, children is a prop, and /* @__PURE__ */ comments tell minifiers that unused calls can be removed. You don't need import React in every JSX file anymore. Other libraries plug in their own runtime with the jsxImportSource option, which is how Preact and Solid use the same syntax.
Components, props and fragments
The first letter of a tag decides how it compiles:
- Lowercase (
<section>) is passed as a string: a built-in HTML or SVG element. - Capitalized (
<Card>) is passed as the value of the variableCard: a component. That's why component names must start with a capital letter, and why<Math />would pass the globalMathobject.
A React function component is a function that takes a props object and returns JSX:
function Greeting({ name, children }) {
return <p className="greeting">Hello, {name}! {children}</p>;
}
const page = <Greeting name="Ada">Welcome back.</Greeting>;
// compiles to: jsxs(Greeting, { name: "Ada", children: "Welcome back." })
Content between a component's tags arrives as props.children. To return several elements without a wrapper, use a fragment: <>...</>, which compiles to the special Fragment type and adds no element to the page.
Elements are just data
Calling jsx() or createElement() doesn't touch the DOM. It returns a plain object describing what you want, and a separate renderer turns the tree into DOM nodes, HTML on a server, or native views (React Native). A tiny runtime and HTML renderer make this concrete:
// A minimal JSX runtime: createElement builds plain objects, render turns them into HTML.
// Compilers turn <tag attr={x}>child</tag> into createElement("tag", { attr: x }, child).
const Fragment = Symbol("Fragment");
function createElement(type, props, ...children) {
return { type, props: props ?? {}, children: children.flat() };
}
const escapeHTML = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
function render(node) {
if (node === null || node === undefined || node === false || node === true) return ""; // skipped
if (typeof node === "string" || typeof node === "number") return escapeHTML(node);
if (Array.isArray(node)) return node.map(render).join("");
const { type, props, children } = node;
if (type === Fragment) return render(children);
if (typeof type === "function") return render(type({ ...props, children })); // a component
const attrs = Object.entries(props)
.filter(([name, value]) => name !== "key" && typeof value !== "function") // events are not HTML
.map(([name, value]) => ` ${name === "className" ? "class" : name}="${escapeHTML(value)}"`)
.join("");
return `<${type}${attrs}>${render(children)}</${type}>`;
}
// What a compiler produces for a component written in JSX:
// function Card({ title, items, showFooter }) {
// return <section className="card"><h2>{title}</h2>
// <ul>{items.map((item) => <li key={item.id}>{item.name}</li>)}</ul>
// {showFooter && <footer>{items.length} items</footer>}</section>;
// }
function Card({ title, items, showFooter }) {
return createElement("section", { className: "card" },
createElement("h2", null, title),
createElement("ul", null, items.map((item) => createElement("li", { key: item.id }, item.name))),
showFooter && createElement("footer", null, items.length, " items"));
}
const items = [{ id: 1, name: "Apple" }, { id: 2, name: "<b>Bold</b> Banana" }];
const tree = createElement(Fragment, null,
createElement(Card, { title: "Fruit", items, showFooter: true }),
createElement(Card, { title: "Empty", items: [], showFooter: false }));
console.log(JSON.stringify(createElement("h2", null, "Fruit")));
console.log(render(tree));
{"type":"h2","props":{},"children":["Fruit"]}
<section class="card"><h2>Fruit</h2><ul><li>Apple</li><li><b>Bold</b> Banana</li></ul><footer>2 items</footer></section><section class="card"><h2>Empty</h2><ul></ul></section>
The renderer calls component functions with their props, skips false, flattens arrays, drops key and event handlers, renames className, and escapes text, so the <b> in the data stays harmless text. React adds the hard parts: keeping state, comparing new and old trees to update only what changed, and attaching event handlers. With a compiler configured to call your function, JSX can describe any tree-shaped data.
Common questions
Why className instead of class?
JSX compiles to JavaScript object properties, and React's props follow the DOM property names (element.className, element.htmlFor). Some other JSX libraries, such as Preact and Solid, accept class directly.
Why does every list item need a key?
When a list changes, React uses keys to tell which item is which, so it can keep each item's DOM and state instead of rebuilding or mismatching them. Keys must be unique among siblings and stable across renders.
Is JSX the same as HTML in a template string?
No. JSX compiles to function calls that build objects, with JavaScript expressions in braces and automatic escaping. A template string is just text: inserting user data into one and assigning it to innerHTML is an injection risk.
Summary
- JSX is syntax for tree-shaped data that compiles to function calls:
jsx(type, props, key)with the modern automatic runtime, orReact.createElement(type, props, ...children)with the classic one. - Attributes become props, children become
props.children, and braces embed any JavaScript expression: conditions with&&and?:, lists withmapandkey, objects, functions and spread props. - Lowercase tags are HTML elements (strings); capitalized tags are components (values). Fragments group elements without a wrapper.
- The calls return plain objects; a renderer such as React DOM turns them into DOM. Text is escaped automatically.
Practice Questions
What's wrong with this component?
function List({ items }) {
return <ul>{items.map((item) => { <li>{item}</li> })}</ul>;
}
Answer
The arrow function has a block body without return, so map produces an array of undefined and the list renders empty. Use an expression body, and add a key:
function List({ items }) {
return <ul>{items.map((item) => <li key={item}>{item}</li>)}</ul>;
}
What does <Button primary onClick={save}>Save</Button> compile to with the classic transform?
Answer
React.createElement(Button, { primary: true, onClick: save }, "Save");
Button is passed as a value because it's capitalized, an attribute without a value is true, and the text becomes a child.
A component shows {messages.length && <Badge count={messages.length} />}. What appears when there are no messages, and how do you fix it?
Answer
A 0 appears. messages.length && ... evaluates to 0, and React renders numbers. Use a boolean condition: {messages.length > 0 && <Badge count={messages.length} />}.
Previous: Bundlers and Transpilers: Vite, esbuild, Rollup, webpack, Babel and TypeScript Compilation
Next: Type Checking with TypeScript: Annotations, Inference, Objects, Arrays and Functions

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.