Elements and JSX

JSX is a function call. Elements are plain objects.

Builds on UI as a function of state.

Chapter 2 ended with a wish: keep writing the screen as view(state), but describe it as data instead of an HTML string, so a renderer can compare the old screen with the new one and change only what differs.

This chapter builds that data. You'll write the function that creates it, createElement, and see that JSX, the HTML-like syntax every React codebase uses, is nothing more than a nicer way to call it. Then you'll look inside real React elements and find the same plain objects. From here on, everything in Part 2 builds one small React in JavaScript, a stage per chapter, with the same function names all the way through.

The problem: strings can't be compared#

Two HTML strings can tell you that the screen changed. They can't tell you what changed. Is the <input> in the new string the same input as in the old one, with a different value? Or a new input? To answer that you'd have to parse both strings into trees and match the nodes, and at that point you've rebuilt half a browser.

So skip the string. Describe each piece of UI as a small object: what kind of thing it is, its properties, its children. A screen becomes a tree of those objects. Objects are cheap to create, easy to keep around, and easy to compare field by field.

{
  type: "li",
  props: { className: "done", children: ["Buy milk"] },
}

That object is an element: a description of a piece of UI. Not a DOM node, not a component. Just data.

Build it: createElement#

Writing those objects by hand is tedious, so write a function that builds them. It takes a type, an object of properties and any number of children:

createElement("li", { className: "done" }, "Buy milk");

Here's the toy's version. It's the whole of stage 3 of our tiny React:

toy.js (stage 3)
// Toy React, stage 3: elements.
// JSX compiles to createElement calls. createElement returns a plain object
// that describes a piece of UI. Nothing touches the DOM yet.

export function createElement(type, config, ...children) {
  const { key = null, ...props } = config ?? {};
  props.children = children
    .flat(Infinity) // children can arrive as arrays, e.g. from list.map(...)
    .filter((child) => child != null && child !== false && child !== true)
    .map((child) => (typeof child === "object" ? child : createTextElement(child)));
  return { type, key: key == null ? null : String(key), props };
}

// Strings and numbers become text elements, so every child has the same shape.
export function createTextElement(text) {
  return { type: "TEXT_ELEMENT", key: null, props: { nodeValue: String(text), children: [] } };
}

// <>...</> compiles to createElement(Fragment, null, ...children).
// In the toy, a Fragment is a component that returns its children.
export function Fragment(props) {
  return props.children;
}

Four decisions in there are worth understanding, because the rest of the toy leans on them:

  • Children go into props.children. A component will receive them like any other prop, which is how children works in React.
  • Children are flattened. createElement("ul", null, items.map(...)) passes an array as one argument. Flattening means a list and hand-written children look the same afterwards.
  • null, false and true disappear. That's what makes {isAdmin && <Badge />} render nothing when the condition is false.
  • Strings and numbers become text elements, objects with the type "TEXT_ELEMENT", so every child has the same { type, props } shape. That keeps the renderer simple. React doesn't do this; it keeps text as plain strings. It's the toy's first labeled simplification.

key is pulled out of the props and stored next to type. You'll see why in chapter 6, where keys tell the renderer which list item is which. For now, notice that a component will never see key in its props.

Try it. Call createElement by hand and look at what comes back.

createElement by hand
import { createElement } from "./toy.js";

const element = createElement(
  "ul",
  { className: "todos" },
  createElement("li", { key: "milk" }, "Buy milk"),
  createElement("li", { key: "dog" }, "Walk dog"),
);

console.log(JSON.stringify(element, null, 2));
Nothing logged yet.

Nothing appeared on a screen, and nothing was supposed to. createElement only describes. Turning descriptions into DOM is the next chapter.

JSX is a function call#

Nobody wants to write nested createElement calls all day. JSX lets you write the same thing as markup:

<ul className="todos">
  <li key="milk">Buy milk</li>
  <li key="dog">Walk dog</li>
</ul>

Browsers don't understand JSX. A compiler (Babel, SWC, esbuild, TypeScript, Sucrase) rewrites it into function calls before the code runs. With the classic transform, you tell the compiler which function to call, and every tag becomes one call to it. The sandbox below is set up to compile JSX to our toy's createElement. Open the Compiled tab to see exactly what runs.

JSX compiled to the toy's createElement
import { createElement, Fragment } from "./toy.js";

function Item({ text }) {
  return <li className="item">{text}</li>;
}

const todos = ["Buy milk", "Walk dog"];
const showDone = false;

const element = (
  <>
    <h3>Todos ({todos.length})</h3>
    <ul>
      {todos.map((t) => (
        <Item key={t} text={t} />
      ))}
      {showDone && <li>Read</li>}
    </ul>
  </>
);

// Functions don't survive JSON.stringify, so print them by name.
const show = (key, value) => (typeof value === "function" ? `ƒ ${value.name}` : value);
console.log(JSON.stringify(element, show, 2));
Nothing logged yet.

The Compiled tab shows the whole trick. A few rules fall out of it:

  • Attributes become one props object. className="item" becomes { className: "item" }. That's why it's className and not class: props are JavaScript property names, and the DOM property is className.
  • Braces are plain JavaScript expressions. {todos.length} and {todos.map(...)} are passed through as arguments. Statements (if, for) can't go in braces because a function argument has to be an expression. That's why conditionals in JSX are && and ? :, and loops are map.
  • Children are the remaining arguments, in order.
  • Lowercase tags become strings, capitalized tags become variables. <li> compiles to createElement("li", ...), while <Item> compiles to createElement(Item, ...), passing the function itself. A lowercase <item> would be the string "item", an unknown HTML tag.
  • A fragment, <>...</>, is createElement(Fragment, null, ...). It lets you return siblings without a wrapper element. In the toy, Fragment is a component that returns its children.
  • A JSX expression is one function call, so it returns one value. That's why two sibling tags need a parent or a fragment: return <h3 /> <ul /> would be two expressions with nothing joining them.
From JSX to a tree of objects
what you write (JSX)<ul className="todos">  <li>Buy milk</li>  <Item text="Read" /></ul>no objects exist yet
Step 1 of 5

You write JSX: markup-like syntax inside JavaScript. The browser can't run it, so a compiler rewrites it before your code ships.

Build itCompile JSX by hand

Write the createElement calls that this JSX compiles to, in byHand.js, without using JSX:

<form className="add">
  <input name="title" placeholder="Title" />
  <button type="submit">Add</button>
</form>

Press Check to compare your object with the one the compiler produces.

import { createElement } from "./toy.js";

// Rewrite the JSX from the prompt as createElement calls. No JSX allowed.
export const byHand = createElement("form", null);
Nothing logged yet.

The real thing: React elements#

React's createElement does the same job as the toy's and returns the same kind of object. Here it is, called directly, in development mode:

A real React element is a plain object
import { createElement } from "react";

function Greeting({ name }) {
  return createElement("h1", null, "Hello, ", name);
}

const element = createElement(Greeting, { name: "Ada", key: "g1" });

console.log("$$typeof:", element.$$typeof);
console.log("type is the function itself:", element.type === Greeting);
console.log("key:", element.key);
console.log("props:", element.props);
console.log("frozen in development:", Object.isFrozen(element));

const one = createElement("p", null, "only child");
const two = createElement("p", null, "first", "second");
console.log("one child:", one.props.children);
console.log("two children:", two.props.children);

// Symbols don't survive JSON, and neither does $$typeof.
console.log(JSON.stringify(createElement("p", { id: "x" }, "hi")));
Nothing logged yet.

Line by line:

  • type, key and props are what the toy has. key was pulled out of the props, exactly as in the toy. The component, Greeting, hasn't been called: an element only describes.
  • props.children is a single value when there's one child and an array when there are several, and missing when there are none. The toy always uses an array and turns text into objects; React keeps strings as strings.
  • $$typeof marks the object as a genuine React element, with a Symbol (in React 19, Symbol.for("react.transitional.element")). It's a security measure. If a server returns JSON that you accidentally render as a child, a crafted object could pretend to be an element with dangerous props. A Symbol can't be written in JSON, so JSON can never produce a real element, and React refuses objects without the right $$typeof.
  • Frozen. In development React freezes elements and their props, so mutating one throws in strict-mode code. Elements are immutable snapshots: to change the UI, you create new ones.
  • _owner and _store in the JSON line are development-only bookkeeping (which component created the element, and validation flags). Production elements are just $$typeof, type, key, ref and props.

React 19.0 In React 19, ref is a regular prop on function components. You'll still see a ref field on production elements, but reading element.ref is deprecated and warns in development; read element.props.ref instead.

The automatic runtime: jsx() instead of createElement#

The classic transform has two annoyances: every file needs React in scope, and createElement has to separate key from the props at runtime. React 17 introduced the automatic runtime, modern toolchains use it by default, and it emits a different function:

import { jsx as _jsx } from "react/jsx-runtime";

_jsx("li", { className: "item", children: "Buy milk" }, "milk");

Three differences from createElement:

  • The import is added by the compiler, from react/jsx-runtime. You no longer import React to use JSX.
  • Children are passed inside the props object, not as extra arguments.
  • key is a separate third argument, so the runtime doesn't have to dig it out of the props.

Elements with several static children call jsxs instead (the "s" means the children array was written out literally, so React doesn't have to check it for keys), and development builds usually emit jsxDEV from react/jsx-dev-runtime, which records extra debugging information. They all return the same element object. This sandbox uses the automatic runtime, like any modern React project. Check the Compiled tab.

What the automatic runtime emits
import { createRoot } from "react-dom/client";

function Greeting({ name }) {
  return <h1 className="hello">Hello, {name}</h1>;
}

const element = <Greeting key="g1" name="Ada" />;
console.log(element.type === Greeting, element.key, element.props);

createRoot(document.getElementById("root")).render(element);
Nothing logged yet.

In the compiled output, <Greeting key="g1" name="Ada" /> became _jsx(Greeting, { name: "Ada" }, "g1"), and the <h1> with two children ("Hello, " and name) became _jsxs with a children array. Then createRoot(...).render(element) is the moment React actually turns the description into DOM. The toy gets its own render in the next chapter.

Elements, components and instances#

Three words get mixed up in interviews, so pin them down now:

  • A component is a function (or a class) that returns elements: Greeting.
  • An element is the plain object describing what to render: { type: Greeting, props: { name: "Ada" } }. Cheap, immutable, thrown away and recreated on every render.
  • An instance is what the renderer keeps alive between renders for a mounted component: its state, its DOM node, its place in the tree. In React that bookkeeping is a fiber (chapter 7). You never create one yourself.

<Greeting /> creates an element. It doesn't call Greeting. React calls it later, when and as often as it needs to. That's why a component has to be pure: it gets called on React's schedule, not yours.

Pitfalls#

Check your understanding#

PredictWhat does this log?

With the toy from this chapter:

let calls = 0;
function Avatar({ size }) {
  calls++;
  return <img width={size} />;
}

const el = <Avatar size={48} key="me" />;
console.log(typeof el.type, el.key, el.props.size, el.props.key, calls);
Quick checkCapital letters

What does <Button label="Save" /> compile to with the automatic runtime?

Explain it out loudWhat is JSX, really?

An interviewer asks: "What is JSX, and what's a React element? Is JSX HTML?"

Interview angle

Say it in 30 seconds

JSX is syntax for function calls, not HTML. A compiler turns each tag into a call: today jsx(type, props, key) from react/jsx-runtime, before React 17's automatic runtime React.createElement(type, props, ...children). The call returns a React element, a plain immutable object with type, key and props, plus a $$typeof symbol so JSON can't forge one. Lowercase tags pass strings like "div"; capitalized tags pass the component function itself. Creating an element doesn't call the component. It's a cheap description that React later compares with the previous one.

What does JSX compile to?

basic

What is a React element, and how is it different from a component?

basic

Why do React elements have a $$typeof property?

intermediate

Why must component names start with a capital letter?

basic

Why does a component have to return a single root, and what does a Fragment do?

intermediate

What changed with the automatic JSX runtime, and why?

senior

Recap#

  • An element is a plain object describing UI: type, key, props (with children inside props). Not a DOM node, not a component.
  • JSX is a function call. Classic runtime: createElement(type, props, ...children). Automatic runtime (React 17+): jsx(type, props, key) from react/jsx-runtime, with children inside props.
  • Lowercase tags become strings, capitalized tags pass the component itself. Creating an element never calls the component.
  • Real React elements carry $$typeof, a Symbol that JSON can't forge, and are frozen in development.
  • The toy so far: createElement, createTextElement and Fragment, with text wrapped in objects and children always an array (React keeps text as strings).

Sources#