Sub topic 6
What JSX compiles to
This chapter assumes you can read JSX and write function components, and that you know how props and the children prop work. You should also be comfortable with object spread and arrow functions. Here you will see what the build tools turn your JSX into and why that explains several rules you have already met.
JSX is not understood by the browser
Browsers and Node.js cannot run JSX. A compiler such as Babel, SWC, esbuild, or the TypeScript compiler rewrites every JSX element into an ordinary JavaScript function call before the code runs. JSX is syntax sugar for those calls. React itself never sees the angle brackets.
The compile step happens at build time. The calls run at render time, every time your component function runs.
The automatic runtime
Current tooling uses the automatic JSX runtime. The compiler inserts an import from react/jsx-runtime for you and rewrites each element into a jsx call. The first argument is the element type. The second is one props object that holds the attributes and the children together.
import { jsx as _jsx } from 'react/jsx-runtime';
// Source: <h1 className="title">Hi</h1>
const element = _jsx('h1', { className: 'title', children: 'Hi' });Two things follow from this shape:
- Attribute names are object keys. This is why JSX uses
classNameand notclass. Bothclassandforare reserved words in JavaScript, and DOM property names are camelCase. - Children are not special syntax. They are the
childrenentry of the props object, which is why a component reads them asprops.children.
Nested elements and multiple children
When an element has more than one child, the compiler uses jsxs instead of jsx and passes the children as an array. The extra s tells React the array is static, so it does not need to warn about missing keys for it.
import { jsx as _jsx, jsxs as _jsxs } from 'react/jsx-runtime';
// Source:
// <ul>
// <li>Tea</li>
// <li>Coffee</li>
// </ul>
const element = _jsxs('ul', {
children: [
_jsx('li', { children: 'Tea' }),
_jsx('li', { children: 'Coffee' }),
],
});A single child is passed directly, not wrapped in an array. So props.children can be one value, an array, or undefined. If your component needs to loop over children, use React.Children.toArray(children) instead of assuming an array.
Components versus built-in elements
The compiler decides how to write the first argument by looking at the first letter of the tag name.
| JSX tag | First argument after compiling | Meaning |
|---|---|---|
| `<div>` | `'div'` (a string) | A built-in DOM element |
| `<Greeting>` | `Greeting` (a variable) | Your component function |
| `<ui.Button>` | `ui.Button` (a property access) | A component stored on an object |
| `<greeting>` | `'greeting'` (a string) | An unknown DOM tag, not your component |
This is the reason component names must start with a capital letter. A lowercase name becomes a string, and React then tries to create a DOM element with that tag. The component is never called.
Because a capitalized tag compiles to a plain variable reference, the variable must be in scope. Importing a component and never using it as a tag is fine for the compiler. Using a tag that you never imported produces a ReferenceError at render time, not at compile time.
Expressions and attributes become arguments
Anything inside curly braces is copied into the call as a normal JavaScript expression. The compiler adds no logic of its own.
import { jsx as _jsx } from 'react/jsx-runtime';
// Source: <img className="avatar" src={user.imageUrl} style={{ width: 64 }} />
const element = _jsx('img', {
className: 'avatar',
src: user.imageUrl,
style: { width: 64 },
});The double braces in style={{ width: 64 }} are one pair of JSX braces around an object literal. This also explains conditional rendering. In {isAdmin && <AdminPanel />}, the && expression is evaluated first, and its result (false or an element) becomes the child value. React skips false, null, and undefined when it renders.
Spread attributes become object spread:
import { jsx as _jsx } from 'react/jsx-runtime';
// Source: <Button {...props} disabled />
const element = _jsx(Button, { ...props, disabled: true });An attribute with no value, like disabled, becomes true. Order matters here, as it does in any object literal. A later attribute overrides an earlier one with the same name.
Keys are not props
The key attribute is pulled out of the props object and passed as a separate third argument.
import { jsx as _jsx } from 'react/jsx-runtime';
// Source: <li key={todo.id}>{todo.text}</li>
const element = _jsx('li', { children: todo.text }, todo.id);React uses the key to match elements between renders, but it does not forward it to your component. Reading props.key inside a component gives undefined and triggers a warning. If a child needs the id, pass it again under a different name, such as id or todoId.
Fragments
A fragment, written <>...</>, compiles to a call whose type is the Fragment export from the runtime. Fragments exist only inside React's element tree and add nothing to the DOM.
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from 'react/jsx-runtime';
// Source:
// <>
// <dt>{label}</dt>
// <dd>{value}</dd>
// </>
const element = _jsxs(_Fragment, {
children: [
_jsx('dt', { children: label }),
_jsx('dd', { children: value }),
],
});The short syntax <> cannot take a key. When you need a key, for example when mapping each item to a pair of rows, write <Fragment key={item.id}> with Fragment imported from react.
What the call returns
A jsx call returns a React element. This is a small plain object that describes what you want on screen. It has fields such as type, key, and props. It is not a DOM node and it does nothing on its own. React reads the tree of these objects, compares it with the previous tree, and updates the real DOM.
You can see this without any JSX at all. This script uses createElement, the older API that the automatic runtime replaces. It needs the react package installed and "type": "module" in package.json.
import { createElement } from 'react';
const element = createElement('h1', { className: 'title' }, 'Hi');
console.log(element.type);
console.log(element.props);It prints h1, then { className: 'title', children: 'Hi' }. The props object has the same shape the automatic runtime produces.
The classic runtime
Older projects use the classic runtime. It compiles every element to React.createElement(type, props, ...children). Children are passed as extra arguments, and the call has no jsxs variant.
import React from 'react';
// Source: <h1 className="title">Hi</h1>
const element = React.createElement('h1', { className: 'title' }, 'Hi');With the classic runtime, every file that contains JSX must have React in scope, because the compiled output refers to it by name. If you forget the import, you get ReferenceError: React is not defined. The automatic runtime removes that requirement.
You choose the runtime in your tool configuration. In TypeScript, set the jsx option:
{
"compilerOptions": {
"jsx": "react-jsx"
}
}The value react-jsx selects the automatic runtime and react selects the classic one. Babel's @babel/preset-react has a runtime option with the values automatic and classic. In development builds, the tools import jsxDEV from react/jsx-dev-runtime, which records source locations for better warnings. Your code does not change.
Common errors this explains
- Adjacent JSX elements must be wrapped. A function can return only one value, and two sibling calls are two values. A fragment makes them one.
- A lowercase component renders as an unknown tag. The name compiled to a string. Capitalize it.
React is not defined. The project uses the classic runtime but the file does not import React. Switch to the automatic runtime or add the import.props.keyis undefined. Keys are the third argument, not part of props.- Objects are not valid as a React child.
{user}puts a plain object inchildren. Render a field such asuser.nameinstead.
Exercise
Write the automatic-runtime output (using _jsx and _jsxs) for this JSX: <Card title="Hi"><p>One</p><p>Two</p></Card>. Which call is used for the outer element, and why?
Show answer
_jsxs(Card, { title: 'Hi', children: [_jsx('p', { children: 'One' }), _jsx('p', { children: 'Two' })] }). The outer element uses _jsxs because it has two children, which are passed as an array. Each p has one child, so it uses _jsx. The first argument is the variable Card, not the string 'Card', because the tag name is capitalized.
Exercise
A developer writes <product-list items={items} /> for a component named ProductList, and nothing renders from their component. What does this tag compile to, and what is the fix?
Show answer
It compiles to _jsx('product-list', { items: items }), so the first argument is a string and React treats it as an unknown DOM tag. The fix is to use <ProductList items={items} />, which compiles to _jsx(ProductList, { items: items }) and refers to the component function.
Exercise
Why does props.key read as undefined inside a component rendered as <Row key="a" label="x" />, and how can the component still receive the value?
Show answer
The compiler passes key as a separate third argument to jsx, so it is never placed in the props object. To give the component the value, pass it under another name, for example <Row key="a" rowId="a" label="x" />, and read props.rowId.