Building React's Render Method from Scratch
Write your own createElement and render to see how React works.
When you write React every day it's easy to treat ReactDOM.render as magic.
You write some JSX, hand it to ReactDOM.render and a page shows up. The basic
idea is a lot simpler than it seems: JSX turns into plain objects, and render
turns those objects into DOM nodes.
Let's build our own createElement and render functions in about 40 lines of
JavaScript to see how it works.
JSX is just function calls. Each element is an object that describes a DOM node, and render walks those objects and creates the real nodes.
What does JSX compile to?
Browsers don't understand JSX, so a compiler turns it into function calls. This JSX:
const element = (<div id="app"><h1>Hello</h1><p>From scratch</p></div>)
Compiles to this:
const element = React.createElement("div",{ id: "app" },React.createElement("h1", null, "Hello"),React.createElement("p", null, "From scratch"))
The first argument is the type, the second is the props (or null when there
aren't any), and everything after that is the children.
Building createElement
createElement only needs to return an object. The children go into props,
the same way React gives you props.children:
function createElement(type, props, ...children) {return {type,props: {...props,children: children.flat().map((child) =>typeof child === "object" ? child : createTextElement(child)),},}}function createTextElement(text) {return {type: "TEXT_ELEMENT",props: {nodeValue: text,children: [],},}}
Text like "Hello" comes in as a string, not an object. Wrapping it in a
TEXT_ELEMENT object means every child has the same shape, so render doesn't
need a special case for each one. The .flat() handles arrays of children,
like when you .map() over a list inside your JSX.
Calling our version gives us a plain object we can log:
createElement("h1", { id: "title" }, "Hello")// {// type: "h1",// props: {// id: "title",// children: [// { type: "TEXT_ELEMENT", props: { nodeValue: "Hello", children: [] } },// ],// },// }
Building render
render takes one of those objects and a container DOM node. It creates the
node, sets its props, renders each child into it and appends it to the
container:
function render(element, container) {const dom =element.type === "TEXT_ELEMENT"? document.createTextNode(""): document.createElement(element.type)Object.keys(element.props).filter((key) => key !== "children").forEach((name) => {if (name.startsWith("on")) {// onClick -> clickconst eventType = name.toLowerCase().substring(2)dom.addEventListener(eventType, element.props[name])} else {dom[name] = element.props[name]}})element.props.children.forEach((child) => render(child, dom))container.appendChild(dom)}
A few things are happening here:
- Text elements get a text node. Its
nodeValuegets set in the props loop like any other prop. childrenis skipped since those get rendered separately.- Props that start with
on, likeonClick, are attached as event listeners. - Everything else is set right on the DOM node, so
idandclassNamework just like they do in React. - render calls itself for each child, which builds the whole tree.
Using JSX with our own createElement
Now we can tell the compiler to use our function instead of
React.createElement. The /** @jsx createElement */ comment at the top of a
file is called a pragma, and it works with the compiler's classic JSX runtime.
The easiest way to try this is a single HTML file that loads a compiler, like Babel standalone, in the browser:
<!-- index.html --><div id="root"></div><script src="https://unpkg.com/@babel/standalone@7.16.7/babel.min.js"></script><script type="text/babel">/** @jsx createElement */// ...createElement, createTextElement and render from aboveconst element = (<div id="app"><h1>Hello</h1><button onClick={() => alert("Clicked!")}>Click me</button></div>)render(element, document.getElementById("root"))</script>
Open the file in your browser and you'll see the heading and a working button.
That last line looks just like ReactDOM.render(element, root). Pretty nifty!
What does real React add?
Our render only knows how to build the DOM once. Call it again and you get a second copy appended to the page. Real React does a lot more:
- Reconciliation: when state changes, React compares the new elements with the previous ones (the virtual DOM diff) and only updates the DOM nodes that changed.
- Fibers: since React 16, rendering is split into small units of work that can be paused and resumed. React 18 is in the works and builds on this for concurrent rendering.
- Function components and hooks: React calls your components as functions and
keeps track of state like
useStatebetween renders.
But at its core it's the same idea: elements are objects, and render turns them into DOM nodes.
This post was inspired by Build your own React by Rodrigo Pombo, which goes all the way through fibers and hooks if you want to keep going.
Have some feedback on this post? .