Rendering elements

Turn element objects into DOM, with components and props.

Builds on Elements and JSX.

In chapter 3 you built createElement and saw that JSX produces a tree of plain objects. A description is useless until something acts on it, though. This chapter writes the toy's render: the function that walks an element tree and builds real DOM from it, calling your components along the way.

By the end the toy can render components with props and children, which is enough for a small app. It will also rebuild the entire page every time you call it, which is chapter 2's innerHTML problem in a new costume. That's on purpose: the next chapter fixes it, and you'll want to have felt it first.

The problem: a description that does nothing#

Here's what we have so far:

const element = <h1 className="title">Hello</h1>;
// { type: "h1", key: null, props: { className: "title", children: [ {TEXT_ELEMENT "Hello"} ] } }

To put that on screen, something has to read the object and translate it into DOM calls: create an h1, set its className, create a text node, append it, attach the whole thing to the page. And because elements nest, it has to do that for every child, recursively. When it meets a component, it has to call it to find out what to render. That something is render(element, container).

Build it: render#

The toy's stage 4 splits the job into three pieces.

1. Make one DOM node from one element. Text elements become text nodes; anything else becomes document.createElement(type). Then its props are applied.

export function createDom(element) {
  const dom = element.type === "TEXT_ELEMENT" ? document.createTextNode("") : document.createElement(element.type);
  updateDom(dom, {}, element.props);
  return dom;
}

2. Apply props to a DOM node. updateDom(dom, prevProps, nextProps) applies the difference between two props objects. Today prevProps is always empty, but the next chapter calls it with real old props, so it's written for that from the start. It handles four kinds of prop:

  • children is skipped. Children aren't attributes; the recursion handles them.
  • onSomething props are event handlers: onClick listens for "click". The toy gives each DOM node one real listener per event type, which calls whatever handler the latest props supplied. That way a fresh arrow function on every render doesn't mean removing and re-adding listeners.
  • style objects are copied onto dom.style.
  • Everything else is set as a DOM property when the node has one (className, value, checked, nodeValue for text) and as an attribute otherwise (data-id, aria-label). Properties are why JSX says className: that's the DOM property's name.

3. Walk the tree. mount handles one element and recurses into its children. A host element (a string type like "li") becomes a DOM node, its children are mounted into it, and then it's appended to its parent. A component (a function type) is called with its props, and whatever it returns is mounted in its place:

function mount(element, parentDom) {
  if (typeof element.type === "function") {
    const output = element.type(element.props);
    for (const child of toChildArray(output)) mount(child, parentDom);
    return;
  }
  const dom = createDom(element);
  for (const child of element.props.children) mount(child, dom);
  parentDom.appendChild(dom);
}

export function render(element, container) {
  container.replaceChildren(); // throw the old DOM away
  mount(element, container);
}

toChildArray normalizes what a component returns: an element, a string, null, or an array (a fragment returns its children array). Notice that a component never gets a DOM node of its own. It's replaced by its output. Open the browser's element inspector on any React app and you'll see only divs and lis, never <TodoList>.

Also notice when the DOM goes on screen: a node is appended to its parent after its own children are mounted. The whole subtree is built off screen and attached with a single appendChild at the end, so the browser lays it out once instead of after every node.

render() walks the element tree
Elementsh3liItemliItemuldivAppDOM<div id="root"> (empty)
Step 1 of 8

render(<App />, root) starts with one element. Its type is a function, so there's no DOM node to make for it.

Here's the whole of stage 4 running a small app. The Card component shows children at work: whatever you nest inside <Card> arrives as props.children, and Card decides where it goes.

The toy renders components
import { createElement, render } from "./toy.js";

function Item({ text, done }) {
  return <li style={{ textDecoration: done ? "line-through" : "none" }}>{text}</li>;
}

function Card({ title, children }) {
  return (
    <section className="card">
      <h3>{title}</h3>
      {children}
    </section>
  );
}

function App({ todos }) {
  const left = todos.filter((t) => !t.done).length;
  return (
    <Card title="Todos">
      <ul>
        {todos.map((t) => (
          <Item key={t.id} text={t.text} done={t.done} />
        ))}
      </ul>
      <p>{left} left</p>
    </Card>
  );
}

const todos = [
  { id: 1, text: "Buy milk", done: true },
  { id: 2, text: "Walk dog", done: false },
  { id: 3, text: "Read", done: false },
];

render(<App todos={todos} />, document.getElementById("root"));

Props are a one-way street#

A component gets its props as an argument and returns elements. Data flows down: App passes text to Item, Item can't send anything back except by calling a function it was given. And a component must treat props as read-only. If Item did props.text = "changed", it would be mutating the parent's element, which the parent may reuse. In development, React freezes props objects so that line throws. The toy doesn't bother, which is fine for a toy.

Build itTeach render about components

This render only knows about host elements. Rendering a component crashes, because document.createElement gets a function instead of a tag name. Add support for function components in mount: call the component with its props and mount whatever it returns in its place. Remember that a component can return an element, a string, null, or an array. Press Check when you think it works.

import { createDom, toChildArray } from "./toy.js";

function mount(element, parentDom) {
  // TODO: if element.type is a function, call it with element.props
  // and mount whatever it returned (there may be zero, one or many children).

  const dom = createDom(element);
  for (const child of element.props.children) mount(child, dom);
  parentDom.appendChild(dom);
}

export function render(element, container) {
  container.replaceChildren();
  mount(element, container);
}

Updating means rebuilding#

The toy can draw a screen. Now make it change. Without hooks (that's chapter 8), the way to update is chapter 2's: keep state outside, and call render again with new props whenever it changes. The sandbox also counts how many DOM elements each render creates. Click the button a few times, then try typing in the box.

Re-rendering with the toy
import { createElement, render } from "./toy.js";

// Count DOM elements created, to see what each render costs.
let created = 0;
const createEl = document.createElement.bind(document);
document.createElement = (tag) => (created++, createEl(tag));

let state = { count: 0, name: "" };
const root = document.getElementById("root");

function setState(next) {
  state = { ...state, ...next };
  created = 0;
  render(<App {...state} />, root);
  console.log(`render created ${created} elements`);
}

function App({ count, name }) {
  return (
    <div>
      <button onClick={() => setState({ count: count + 1 })}>Clicked {count} times</button>
      <p>
        <input value={name} placeholder="Type your name" onInput={(e) => setState({ name: e.target.value })} />
      </p>
      <p>Hello, {name || "stranger"}</p>
    </div>
  );
}

setState({});
Nothing logged yet.

Every render creates every element again, five of them here, even when one number changed. And the input loses focus after each letter, for exactly the reason it did in chapter 2: render throws the old input away and builds a new one. We traded HTML strings for objects, but we're still using them like strings.

Hold that thought. Here's the same component with real React, written the same way: state outside, root.render with new props on every change. (flushSync makes React render immediately, so the counter can be read right after. Normally you'd never need it here.)

The same code with createRoot
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";

let created = 0;
const createEl = document.createElement.bind(document);
document.createElement = (tag, options) => (created++, createEl(tag, options));

let state = { count: 0, name: "" };
const root = createRoot(document.getElementById("root"));

function setState(next) {
  state = { ...state, ...next };
  created = 0;
  flushSync(() => root.render(<App {...state} />));
  console.log(`render created ${created} elements`);
}

function App({ count, name }) {
  return (
    <div>
      <button onClick={() => setState({ count: count + 1 })}>Clicked {count} times</button>
      <p>
        <input value={name} placeholder="Type your name" onInput={(e) => setState({ name: e.target.value })} />
      </p>
      <p>Hello, {name || "stranger"}</p>
    </div>
  );
}

setState({});
Nothing logged yet.

The first render creates the elements. After that, React creates nothing: it keeps the same DOM nodes, changes the button's text and the greeting, and leaves the input alone, so you can type normally. Same components, same "render everything" calls, completely different behavior. The difference is that React remembers what it rendered last time and compares. Chapter 5 gives the toy that memory.

The real thing: createRoot and root.render#

React's entry point has the same shape as the toy's, and the toy exports a matching createRoot:

main.jsx
import { createRoot } from "react-dom/client";
import App from "./App";

const root = createRoot(document.getElementById("root"));
root.render(<App />);

What happens inside root.render, mapped to what you just built:

ToyReact
render(element, container)createRoot(container) creates a root once, then root.render(element) renders into it. Call render again to update, root.unmount() to tear down.
Renders synchronously, right nowSchedules a render. The DOM updates shortly after the call returns, not during it. flushSync forces it to happen immediately.
Rebuilds the whole DOM every timeCompares with the previous tree and updates in place (chapter 5).
mount recursion, calling componentsThe render phase walks a tree of fibers, calling components (chapter 7).
createDom + updateDomThe DOM "host config" in react-dom, functions like createInstance and commitUpdate, plus property handling that knows hundreds of HTML and SVG special cases.
One listener per node per event typeOne listener per event type on the root container (event delegation, since React 17), dispatching through the component tree to your handlers as synthetic events.

React 19.0 The old ReactDOM.render(element, container) and ReactDOM.hydrate were deprecated in React 18 and removed in React 19. Use createRoot (and hydrateRoot for server-rendered HTML).

Real React also does a lot of prop translation the toy skips: htmlFor becomes the for attribute, numeric styles like width: 100 get px added for properties that need a unit, defaultValue sets an input's initial value, unknown props on DOM elements produce warnings, and onChange on inputs fires on every keystroke (React wires it to the native input event, unlike the DOM's change event, which waits until the edit is committed, usually on blur). The toy uses onInput to stay honest.

Pitfalls#

Check your understanding#

PredictIn what order?

Using the toy's render, what does this log, in order?

function Child({ name }) {
  console.log("render", name);
  return <li>{name}</li>;
}

function Parent() {
  console.log("render Parent");
  return (
    <ul>
      <Child name="a" />
      <Child name="b" />
    </ul>
  );
}

console.log("before");
const element = <Parent />;
console.log("created");
render(element, document.getElementById("root"));
console.log("after");
Quick checkroot.render in React 19

Which is true of createRoot(container).render(element) in React 19?

Explain it out loudWhat happens on the first render?

An interviewer asks: "Walk me through what happens when you call root.render(<App />) for the first time."

Interview angle

Say it in 30 seconds

Rendering turns an element tree into DOM. The renderer walks the tree depth first: a host element like div becomes a DOM node with its props applied, and a component is called with its props and replaced by whatever it returns, so components never appear in the DOM. A naive renderer rebuilds everything on each update and loses focus and other DOM state. React's entry point is createRoot(container).render(element): it schedules a render, keeps the tree it built, and on later renders updates the existing DOM in place.

How does a renderer treat a component differently from a DOM element like div?

basic

What does createRoot(container).render(<App />) do, and is it synchronous?

basic

Why are props read-only?

basic

If you re-render by building the DOM from scratch each time, what goes wrong?

intermediate

A component passes a new arrow function as onClick on every render. Does the renderer remove and re-add a DOM listener each time?

intermediate

Recap#

  • render(element, container) walks the element tree depth first: host elements become DOM nodes with their props applied, components are called and replaced by what they return.
  • Components never appear in the DOM. A fragment is just a component that returns its children.
  • Props flow down and are read-only. children is a prop like any other.
  • The toy rebuilds the whole DOM on every render, so it has chapter 2's problems: lost focus and wasted work. React keeps the previous tree and updates in place.
  • React's entry point is createRoot(container).render(element). It schedules work rather than rendering during the call. ReactDOM.render was removed in React 19.

Sources#