React / 03
Nesting with createElement
Children, siblings and attributes using plain React.createElement, and why nobody writes UI this way for long.
The target
We want this structure on the page:
<div id="parent">
<div id="child">
<h1>I'm an h1</h1>
<h2>I'm an h2</h2>
</div>
</div>I'm an h1
I'm an h2
Build it, box by box
const parent = React.createElement(
"div",
{ id: "parent" },
React.createElement("div", { id: "child" }, [
React.createElement("h1", { key: "a" }, "I'm an h1"),
React.createElement("h2", { key: "b" }, "I'm an h2"),
])
);
createRoot(document.getElementById("root")).render(parent);Read it from the outside in. Each createElement is one box, and its third argument is what goes inside:
- One child? Pass it directly, like
#parentholding#child. - Several siblings? Wrap them in an array
[ ], like#childholding theh1and theh2. - Attributes? The second argument:
{ id: "parent" }. No attributes? Passnullor{}.
The result is a tree of objects
Since each createElement returns an object, nesting them gives you objects inside objects:
{
type: "div",
props: {
id: "parent",
children: {
type: "div",
props: {
id: "child",
children: [
{ type: "h1", props: { children: "I'm an h1" } },
{ type: "h2", props: { children: "I'm an h2" } }
]
}
}
}
}This object tree is what React compares when your data changes. It's cheap to build and cheap to diff, so React only touches the real DOM where something actually changed.
Now imagine a real page
Two children, each with an h1 and an h2, and it's already hard to see what's inside what. Compare it with JSX, which you'll meet properly in Chapter 3:
const parent = React.createElement("div", { id: "parent" }, [
React.createElement("div", { id: "child1", key: "c1" }, [
React.createElement("h1", { key: "a" }, "I'm an h1"),
React.createElement("h2", { key: "b" }, "I'm an h2"),
]),
React.createElement("div", { id: "child2", key: "c2" }, [
React.createElement("h1", { key: "a" }, "I'm an h1"),
React.createElement("h2", { key: "b" }, "I'm an h2"),
]),
]);const parent = (
<div id="parent">
<div id="child1">
<h1>I'm an h1</h1>
<h2>I'm an h2</h2>
</div>
<div id="child2">
<h1>I'm an h1</h1>
<h2>I'm an h2</h2>
</div>
</div>
);Same tree, same objects. JSX is just a nicer way to write createElement calls. A compiler turns it back into them before the browser runs it.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
