Capítulo 81 de 116

Chapter 81: createElement

Core Idea

createElement(type, props, ...children) is the plain-JavaScript function JSX compiles down to — every <Component prop={x}>child</Component> you write becomes a createElement call under the hood, callable directly when writing React without JSX at all.

Key Concepts

  • Signature: createElement(type, props, ...children)type is a string ('div') for a host element or a component reference for a custom one; props is the props object (or null); remaining arguments become children.
  • JSX is sugar over this call: <Greeting name="Ada" /> compiles to createElement(Greeting, { name: 'Ada' }) — understanding this equivalence explains why JSX has the constraints it does (e.g. why a capitalized tag name resolves to a variable reference, not a string).
  • Rarely called directly in modern code — JSX is used almost everywhere in practice; calling createElement manually is mainly relevant for tooling that generates React trees programmatically without a JSX transform step, or for understanding what a JSX expression actually produces.
  • Returns a plain, lightweight object describing the element (its type, props, and children) — not a DOM node and not a component instance; this is the "blueprint" object referenced in Ch 16's discussion of why conditional JSX branches aren't separate stateful "instances."

Code Examples

// These two are equivalent:
const a = <Greeting name="Ada" />;
const b = createElement(Greeting, { name: 'Ada' });
  • What it demonstrates: the direct JSX-to-function-call equivalence — createElement is the runtime call, JSX is the readable syntax that compiles to it.

Key Takeaways

  1. Every piece of JSX you write is, at compile time, converted into a createElement (or an equivalent JSX-runtime) call — there's no separate "JSX engine" at runtime.
  2. Calling this directly is rarely needed in application code — it's mainly relevant to library/tooling authors generating React trees without JSX.
  3. Its return value is a plain description object, not a rendered DOM node — rendering happens later, during React's render/commit cycle (Ch 22).

Connects To

  • Ch 13 (Writing Markup with JSX): the syntax this function is the compiled target of.
  • Ch 16 (Conditional Rendering): the "elements are lightweight blueprints, not instances" idea this function's return value underpins.