From JSX to pixels
Elements & JSX
Lesson 1 of 249 min
In this lesson
Here is a question I used to get wrong. When I write this:
const view = <Greeting name="Ada" />;when does Greeting run? For a long time my mental model was "right there". It
looks like a call, after all. It is not. That line never calls Greeting, and
understanding what it does instead is the base for everything else React does:
re-rendering, skipping work, pausing a render halfway.
So in this lesson I write the function that JSX compiles to, point the compiler at it, and print what comes out.
The target: a plain object
Before anything reaches the screen, React needs to know what I want there. Which tag or component, with which props, wrapping which children. I hand it that as a plain object, one per tag. React reads it, compares it with the one from the last render, and throws it away. Nothing is cheaper to build and throw away than a plain object, and four fields are enough.
export const REACT_ELEMENT_TYPE = Symbol.for('mini-react.element');
export const REACT_FRAGMENT_TYPE = Symbol.for('mini-react.fragment');
export type Key = string | null;
export interface ReactElement<P = any> {
$$typeof: symbol;
type: any;
key: Key;
props: P;
}
export type ReactNode = ReactElement | string | number | boolean | null | undefined | ReactNode[];type is what to draw: a string such as 'li' for a DOM tag, or a function for
a component. key is a string or null. props is everything else.
$$typeof is a marker that says "this object is an element". It is a symbol
rather than a string for a reason: a symbol cannot be written in JSON. If my app
renders data that came from a server, nobody can store JSON there that passes as
an element, because the marker does not survive the trip.
The function the compiler calls
I don't get to pick the name or the arguments of this function. The compiler
does. With the "automatic" JSX transform, every tag becomes a call to jsx,
imported from <import source>/jsx-runtime. On a dev server it's jsxDEV from
<import source>/jsx-dev-runtime instead. The arguments are always the same
three, in the same order: the type, an object with the props, and the key. My
job is to put a function at that address that does the right thing with them.
import { REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, type ReactElement, type Key } from './shared';
export const Fragment = REACT_FRAGMENT_TYPE;
export function jsx(type: any, config: any, maybeKey?: any): ReactElement {
let key: Key = null;
if (maybeKey !== undefined) key = '' + maybeKey;
if (config != null && config.key !== undefined) key = '' + config.key;
const props: Record<string, any> = {};
for (const name in config) {
if (name !== 'key') props[name] = config[name];
}
// Elements (and their props) are immutable. Freezing them makes accidental
// mutation throw, exactly like React does in development.
Object.freeze(props);
return Object.freeze({ $$typeof: REACT_ELEMENT_TYPE, type, key, props });
}
// The compiler calls `jsxs` when it built the children array itself
// (two or more children written in the source). Same object either way.
export const jsxs = jsx;
/** The dev transform passes extra debug args; we ignore them. */
export function jsxDEV(type: any, config: any, maybeKey?: any): ReactElement {
return jsx(type, config, maybeKey);
}A few things worth pointing at:
- The key becomes a string.
'' + maybeKeymeanskey={7}andkey="7"are the same key. The second check covers a key that arrives inside the props object, which happens when you spread an object that contains one. - The key is left out of
props. That is whyprops.keyisundefinedinside a component. The key is for React, to tell siblings apart. - Nothing else is special.
childrenis copied like any other prop. So isref, which has been an ordinary prop since React 19. - Both objects are frozen. An element describes one moment. If it could be changed afterwards, comparing it with the next description would mean nothing.
Fragmentis the symbol. For<>…</>the compiler importsFragmentfrom this file and passes it as the type. It is not a component.
jsxs and jsxDEV are names the compiler uses in specific situations. jsxs
is for tags with several children written by hand. jsxDEV is what a dev server
calls, with three extra arguments (a flag, the source location, this) that real
React uses for warnings. Here they all build the same object.
Pointing the compiler at it
Something I didn't notice for years: every file with JSX in it gets an import nobody typed. The compiler adds it.
const view = <Greeting name="Ada" />;import { jsx as _jsx } from 'mini-react/jsx-runtime';
const view = _jsx(Greeting, { name: 'Ada' });I only choose one word of that import, mini-react. That's the import source.
The compiler tacks on /jsx-runtime by itself (/jsx-dev-runtime on a dev
server). So getting this to work comes down to three things. TypeScript needs to
know the name, Vite needs to know it too, and every path the compiled code
imports has to lead to a real file.
TypeScript: where JSX comes from
TypeScript is the one checking my JSX, in the editor and in yarn typecheck,
so it has to agree on the import source. It also needs paths, because
mini-react isn't installed anywhere. It's a folder in my project. Both go in
tsconfig.json:
"jsx": "react-jsx",
"jsxImportSource": "mini-react",
"paths": {
"mini-react": ["./src/mini-react/index.ts"],
"mini-react/*": ["./src/mini-react/*"]
}Vite: compiling and finding the files
TypeScript only checks, though. The code the browser runs is compiled by Vite
(with oxc), so Vite gets the same import source. It also needs an alias, for
the same reason TypeScript needed paths: when the compiled code imports
mini-react/…, Vite has to load it from my folder. In vite.config.ts:
resolve: {
alias: [
{ find: /^mini-react$/, replacement: `${lib}/index.ts` },
{ find: /^mini-react\/(.*)$/, replacement: `${lib}/$1` },
],
},
oxc: { jsx: { runtime: 'automatic', importSource: 'mini-react' } },The files the compiled code imports
A production build imports mini-react/jsx-runtime, and that's the file I just
wrote. The dev server asks for mini-react/jsx-dev-runtime instead, so that
file has to exist too. There's nothing in it. It just passes the same exports
along:
export { jsxDEV, Fragment, jsx, jsxs } from './jsx-runtime';
export type { JSX } from './jsx-runtime';Plain mini-react, with nothing after it, is the package's entry point. That's
where the demo imports its types from:
import { REACT_FRAGMENT_TYPE } from './shared';
export { jsx, jsxs, createElement } from './jsx-runtime';
export type { ReactNode, ReactElement } from './shared';
// `as any` so TypeScript accepts <Fragment> as a JSX tag (it is a symbol, not a function).
export const Fragment = REACT_FRAGMENT_TYPE as any;TypeScript: which tags exist
Even with the compiler sorted out, TypeScript still has opinions about every
tag I write. It wants to know whether li is a tag at all, what props it
accepts, and what type <li>A</li> ends up with. It doesn't guess. It looks for
a namespace called JSX exported from the runtime module and reads the answers
there.
Real React's types list every HTML tag, each with its own props. I'm not
writing all of that for a course, so mini-react takes the lazy route. The index
signature in IntrinsicElements lets any tag through with any props. The rest
is small. Element says a tag's type is a ReactElement,
ElementChildrenAttribute says children arrive in the children prop, and
IntrinsicAttributes lets any tag take a key. This continues
jsx-runtime.ts:
export namespace JSX {
export type Element = ReactElement;
export interface ElementChildrenAttribute {
children: {};
}
export interface IntrinsicAttributes {
key?: string | number | null;
}
export interface IntrinsicElements {
[elementName: string]: any;
}
}createElement: elements without a compiler
Before the automatic transform existed, JSX compiled to
createElement(type, props, ...children). It's also what you'd call by hand if
there were no compiler at all, so I want it around. Its arguments are shaped
differently, though. The key travels inside the props, and the children come in
as extra arguments. So in mini-react it's just a small adapter in front of
jsx. It moves the children into props.children and hands the rest over.
Same file again:
/** Classic API: createElement(type, props, ...children). */
export function createElement(type: any, config: any, ...children: any[]): ReactElement {
const props: Record<string, any> = { ...(config ?? {}) };
if (children.length === 1) props.children = children[0];
else if (children.length > 1) props.children = children;
return jsx(type, props);
}Looking at it
Time to see what all this produces. Below, each piece of the demo's JSX sits
next to the object jsx returns for it, exactly as the demo prints it. The one
cheat is that JSON can't hold symbols or functions, so the demo writes those as
text.
<li key="a">A</li>{
"$$typeof": Symbol(mini-react.element),
"type": "li",
"key": "a",
"props": {
"children": "A"
}
}The A between the tags turned into children: "A". Children really are just
a prop with nicer syntax. The key went in as the call's third argument, so it
never gets anywhere near props.
<Greeting name="Ada" />{
"$$typeof": Symbol(mini-react.element),
"type": function Greeting,
"key": null,
"props": {
"name": "Ada"
}
}This time type is the Greeting function itself, and props holds name.
There's no children because I didn't write anything between the tags. And
there's no h1 either. Greeting would return one, but nobody has called it
yet.
<ul className="menu">
{['a', 'b'].map((id) => (
<li key={id}>{id.toUpperCase()}</li>
))}
</ul>{
"$$typeof": Symbol(mini-react.element),
"type": "ul",
"key": null,
"props": {
"className": "menu",
"children": [
{
"$$typeof": Symbol(mini-react.element),
"type": "li",
"key": "a",
"props": {
"children": "A"
}
},
{
"$$typeof": Symbol(mini-react.element),
"type": "li",
"key": "b",
"props": {
"children": "B"
}
}
]
}
}The map gives back an array of elements, and that array becomes the ul's
children as it is. Each li keeps its key up top, next to its type, with
nothing but children in its props.
<>
<Greeting name="Ada" />
<ul className="menu">…</ul>
</>{
"$$typeof": Symbol(mini-react.element),
"type": Symbol(mini-react.fragment),
"key": null,
"props": {
"children": [{ …Greeting }, { …ul }]
}
}The Fragment turns out to be an ordinary element too, with the second symbol
from shared.ts as its type. Its children are the two objects above, which
makes the whole demo one nested object.
The demo that prints all this doesn't render anything. It writes JSX and prints what the JSX turned into. There's one trick in it. Converting a function to a string gives you its source, and the source the browser has is the compiled one. So an arrow function with JSX inside can show me exactly what the compiler wrote.
The demo's full code
/**
* DEMO — JSX is data
* ==================
*
* Nothing here renders anything. We write JSX, then print what it turned into.
*/
import type { ReactElement } from 'mini-react';
const root = document.getElementById('root')!;
// JSON.stringify drops symbols and functions, so turn them into text first.
function show(element: ReactElement): string {
const readable = (_key: string, v: unknown) =>
typeof v === 'symbol' ? String(v) : typeof v === 'function' ? `function ${v.name}` : v;
return JSON.stringify(element, readable, 2).replace(/"(Symbol\(.+?\)|function \w+)"/g, '$1');
}
function print(title: string, text: string): void {
const h2 = document.createElement('h2');
h2.textContent = title;
const pre = document.createElement('pre');
pre.textContent = text;
root.append(h2, pre);
}
// 1. One element. A function's source is whatever the compiler emitted for it.
const item = () => <li key="a">A</li>;
print('What the compiler wrote', String(item));
print('What that call returns', show(item()));
// 2. A tree: a component, a keyed list, and a Fragment around both.
let calls = 0;
function Greeting(props: { name: string }) {
calls++;
return <h1>Hello, {props.name}</h1>;
}
const tree = (
<>
<Greeting name="Ada" />
<ul className="menu">
{['a', 'b'].map((id) => (
<li key={id}>{id.toUpperCase()}</li>
))}
</ul>
</>
);
print('The tree', show(tree));
print('Times Greeting was called', String(calls));The page starts with the single li. First the call the compiler wrote for it,
then what that call returns.
What the compiler wrote
() => /* @__PURE__ */ _jsxDEV("li", { children: "A" }, "a", false, {
fileName: _jsxFileName,
lineNumber: 27,
columnNumber: 20
}, this)
What that call returns
{
"$$typeof": Symbol(mini-react.element),
"type": "li",
"key": "a",
"props": {
"children": "A"
}
}Look at that _jsxDEV call. The key "a" is already its own argument before
my function even runs.
Then come the tree and the counter. The diagram walks through them one element at a time, and the raw output is underneath if you want it.
Step 1 of 6
- The browser never sees
<li key="a">A</li>. Before it gets there, the compiler swaps the tag for a call,_jsxDEV("li", { children: "A" }, "a", …). The type goes first, then the props, then the key on its own. It’s_jsxDEVbecause this is a dev server (a build writes_jsx), and myjsxDEVjust hands its first three arguments tojsx. - What comes back is a plain, frozen object. The first argument is now
type. The key arrived separately, so it stays out ofprops. And theAbetween the tags is justprops.children, a prop with nicer syntax.$$typeofis the marker that says “this is an element”. - The tree is the same thing, nested, with one card per tag. Like any nested function calls, these run inside out. So
Greeting’s element and bothlis show up first, then theulthat holds thelis, and the Fragment last. Each parent keeps its children inprops.children. - Now
Greeting. Its type is the function itself, and its props are{ name: "Ada" }. No children, since I didn’t write anything between its tags. The<h1>Hello, Ada</h1>it would return doesn’t exist. Only callingGreetingmakes it, and nobody has.callsis still 0. - Then the list.
mapmade oneliper id, and eachkey={id}went out as the third argument. That’s why everylihas its key next to its type and onlychildrenin its props. The key is for React, to tell siblings apart. A component never sees it inprops. - JSX describes things; it doesn’t call them. What you see is the element tree, the data JSX made, with no DOM nodes, no state and no
h1. It isn’t the fiber tree React keeps between renders. I build that by hand in the next lesson. In First paint,beginWorkturns these elements into fibers as it reaches them, and renderingGreeting’s fiber is what finally callsGreetingand creates itsh1.
Highlighted line: 2.
Highlighted line: 4.
// 1. One element. A function's source is whatever the compiler emitted for it.
const item = () => <li key="a">A</li>;
print('What the compiler wrote', String(item));
print('What that call returns', show(item()));Highlighted lines: 8 to 17.
Highlighted lines: 3 to 6, 10, 19.
Highlighted lines: 12 to 13.
Highlighted lines: 18 to 19.
// 2. A tree: a component, a keyed list, and a Fragment around both.
let calls = 0;
function Greeting(props: { name: string }) {
calls++;
return <h1>Hello, {props.name}</h1>;
}
const tree = (
<>
<Greeting name="Ada" />
<ul className="menu">
{['a', 'b'].map((id) => (
<li key={id}>{id.toUpperCase()}</li>
))}
</ul>
</>
);
print('The tree', show(tree));
print('Times Greeting was called', String(calls));Highlighted lines: 22 to 24.
Highlighted lines: 2 to 3, 6 to 9, 14.
Highlighted line: 3.
export function jsx(type: any, config: any, maybeKey?: any): ReactElement {
let key: Key = null;
if (maybeKey !== undefined) key = '' + maybeKey;
if (config != null && config.key !== undefined) key = '' + config.key;
const props: Record<string, any> = {};
for (const name in config) {
if (name !== 'key') props[name] = config[name];
}
// Elements (and their props) are immutable. Freezing them makes accidental
// mutation throw, exactly like React does in development.
Object.freeze(props);
return Object.freeze({ $$typeof: REACT_ELEMENT_TYPE, type, key, props });
}
// The compiler calls `jsxs` when it built the children array itself
// (two or more children written in the source). Same object either way.
export const jsxs = jsx;
/** The dev transform passes extra debug args; we ignore them. */
export function jsxDEV(type: any, config: any, maybeKey?: any): ReactElement {
return jsx(type, config, maybeKey);
}Full output
The tree
{
"$$typeof": Symbol(mini-react.element),
"type": Symbol(mini-react.fragment),
"key": null,
"props": {
"children": [
{
"$$typeof": Symbol(mini-react.element),
"type": function Greeting,
"key": null,
"props": {
"name": "Ada"
}
},
{
"$$typeof": Symbol(mini-react.element),
"type": "ul",
"key": null,
"props": {
"className": "menu",
"children": [
{
"$$typeof": Symbol(mini-react.element),
"type": "li",
"key": "a",
"props": {
"children": "A"
}
},
{
"$$typeof": Symbol(mini-react.element),
"type": "li",
"key": "b",
"props": {
"children": "B"
}
}
]
}
}
]
}
}
Times Greeting was called
0Where Greeting is, there is no h1 and no "Hello, Ada". There is
type: function Greeting and its props, and the counter says 0. JSX stored the
function and never called it. Whoever reads this tree later gets to decide when
to call it, whether to call it at all, and how many times. Notice what else is
missing, too. No DOM nodes, no parent pointers, no state.
That's what I mean by the element tree. It's what JSX produced, and nothing
more. It's also not the fiber tree, and the two are easy to mix up. The fiber
tree is the structure React keeps around between renders, and I build it by
hand in the next lesson, Fiber tree. The two meet in First paint. There,
beginWork turns these elements into fibers as the walk reaches them, and
rendering Greeting's fiber is the moment Greeting finally gets called and
its h1 gets created.
What I left out
- No warnings. Real React checks for missing keys in arrays and for keys passed
through a spread. That is the only reason
jsxsandjsxDEVare separate fromjsx; here they are aliases. - No real typing for tags. Any tag name with any props type-checks.
- The debug fields real React puts on elements in development (owner, stack) are not there.
- Nothing is rendered. The page is built with plain DOM calls because nothing that can draw an element exists yet.
Where this goes
An element is a request. It is rebuilt and thrown away constantly, so it cannot
be where React remembers anything. The next two lessons, Fiber tree and DOM host,
build the object React keeps between renders and the small API it uses to talk to
the DOM. When those three pieces are merged in First paint, something will finally
walk a tree like the one above, call Greeting, and put an h1 on the screen.