React / 02
Hello World, three ways
The same heading built with HTML, then plain JavaScript, then React, so you can see exactly what React adds.
1 · HTML
<div id="root">
<h1>Hello World</h1>
</div>The browser reads it and shows it. Simple, but static: nothing can change without JavaScript.
2 · Plain JavaScript
<div id="root"></div>
<script>
const heading = document.createElement("h1");
heading.textContent = "Hello World from JavaScript";
document.getElementById("root").appendChild(heading);
</script>Three steps: create the element, fill it, attach it. document.createElement is a browser (DOM) API, so this runs with nothing else installed.
3 · React
Load React
Two packages:react(the core) andreact-dom(puts things on a web page).Describe the heading
React.createElementreturns a description of anh1.Create a root and render
Point React at#rootand hand it the description.
<div id="root"></div>
<script type="module">
import React from "https://esm.sh/react@19";
import { createRoot } from "https://esm.sh/react-dom@19/client";
const heading = React.createElement("h1", { id: "title" }, "Hello World from React");
const root = createRoot(document.getElementById("root"));
root.render(heading);
</script>Open that file in a browser and the heading appears. No install and no build step.
createElement's three arguments
React.createElement(type, props, children)| Argument | In our example | What it is |
|---|---|---|
type | "h1" | Which element to make |
props | { id: "title" } | Its attributes, as an object. These are called props. |
children | "Hello World from React" | What goes inside: text or other elements |
So that { } in the middle is just a plain object of attributes. id, className and friends all go there.
It's just an object
Here's the part that clicks everything into place. Log the heading:
console.log(heading);
// { type: "h1", props: { id: "title", children: "Hello World from React" }, key: null, … }A React element is a plain JavaScript object, a description. Nothing is on the screen until root.render() hands that description to react-dom, which creates the real <h1>.
step 1 · describe
React.createElement("h1", { id: "title" }, "Hello")a react element: just an object
{ type: "h1", props: { id: "title", children: "Hello" } }step 2 · react-dom builds it
<h1 id="title">Hello</h1>a real DOM node, inside #root
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
