Lesson 2 of 37Thinking in React
JSX
Write JSX confidently, knowing exactly what it compiles to and where it differs from HTML.
Every React component you write returns JSX, so you will type it thousands of times. Most JSX bugs (a class that does nothing, a style that crashes, two elements with no wrapper) come from treating it as HTML. It is not HTML. It is JavaScript with a markup-shaped syntax, and once you see what it compiles to, the rules stop feeling arbitrary.
JSX is a function call
Browsers cannot run JSX. A build tool (Vite, Next.js, or this site's preview) rewrites it into plain function calls before the code runs. This line:
const title = <h1 className="title">Hello, Ada</h1>;becomes this with the modern JSX transform (React 17 and later):
import { jsx as _jsx } from "react/jsx-runtime";
const title = _jsx("h1", { className: "title", children: "Hello, Ada" });and older setups compiled it to React.createElement("h1", { className: "title" }, "Hello, Ada"). Either way the result is an ordinary JavaScript object called a React element: a description like { type: "h1", props: { className: "title", children: "Hello, Ada" } }. It is not a DOM node. React turns these descriptions into real DOM later.
You can skip JSX entirely and call createElement yourself. Run this: both headings come out identical.
Nested JSX becomes nested calls, so a component returns a tree of these objects. React walks that tree to build the page.
The outer <div className="card"> becomes one call whose children prop is an array of the inner elements.
Because JSX is just values, you can store it in variables, return it from functions, put it in arrays and pass it as arguments.
<p>Hi</p> evaluate to in a React component?Curly braces: a window into JavaScript
Inside JSX, { } means "evaluate this JavaScript expression and put the result here". Any expression works: variables, math, function calls, ternaries, .map(). Statements like if or for do not, because they do not produce a value.
What gets displayed depends on the value: strings and numbers show as text, true, false, null and undefined show nothing, and arrays show each item. Objects cannot be rendered directly ({user} throws "Objects are not valid as a React child").
What text does this paragraph show on screen?
const name = "Sam";
const count = 0;
<p>{name}{false}{null}{undefined} has {count} items</p>Attributes: camelCase JavaScript names
Since JSX turns into JavaScript objects, attribute names follow the DOM's JavaScript property names, not HTML's.
| HTML | JSX | Why |
|---|---|---|
class="card" | className="card" | class is a reserved word in JavaScript |
for="email" | htmlFor="email" | for is a reserved word too |
onclick="..." | onClick={handleClick} | Events are camelCase and take a function, not a string |
style="color: red; font-size: 14px" | style={{ color: "red", fontSize: 14 }} | Style is an object with camelCase keys; numbers mean px |
tabindex="0" | tabIndex={0} | camelCase, and you can pass a number |
Two exceptions keep their dashes: aria-* and data-* attributes stay exactly as in HTML (aria-label="Close", data-id="7").
Notice the double braces in style={{ color: "red" }}. The outer pair means "JavaScript here", the inner pair is the object literal. Strings use quotes (className="card"); anything else uses braces (tabIndex={0}, disabled={true}).
None picked yet
One root, fragments, self-closing tags
A component returns one value, and JSX tags are function calls, so two sibling tags side by side would be like return f() g(). Wrap them in a parent. If you do not want an extra <div> in the DOM, use a fragment: <>...</>.
// Error: adjacent JSX elements must be wrapped
return (
<h2>Title</h2>
<p>Body</p>
);
// Fine: a fragment groups them without adding a DOM node
return (
<>
<h2>Title</h2>
<p>Body</p>
</>
);The long form <Fragment key={id}> (imported from react) exists for the one case where a fragment needs a key, which you will meet in the lists lesson.
Other rules that bite people coming from HTML:
- Every tag must close.
<img>and<br>become<img />and<br />. Any element with no children may self-close:<div />. - Comments go inside braces:
{/* like this */}. An HTML comment<!-- -->is a syntax error. - Wrap multi-line JSX in parentheses after
return. Without them, areturnfollowed by a newline returnsundefined(automatic semicolon insertion).
Put the journey of a JSX tag in order.
- Tap the steps below in the right order.
Escaping: safe by default
What if a user's name is <img src=x onerror="stealCookies()">? In React, text inside braces is always escaped: React sets it as text, never as HTML, so the angle brackets are shown literally and no script runs. That makes the most common web attack, cross-site scripting (XSS), very hard to cause by accident.
When you truly need to inject HTML (say, an article body produced by your own Markdown renderer), React makes you type a deliberately scary name: dangerouslySetInnerHTML={{ __html: html }}. Run this and compare the two lines.
Profile card in JSX
Render a profile card for the user object using JSX. The checks look for exactly this structure:
- A wrapper
<div>with the classcard. - An
<h2>with the user's name. - A
<p>with the classroleshowing the role in uppercase (use an expression in braces). - A
<span>with the classstatus, whose text isOnlineifuser.onlineis true andOfflineotherwise, and whose inline style setscolortogreenwhen online andgraywhen offline. - A
<label>readingMessagethat is connected to an<input type="text">withid="msg".
Ada
ENGINEER
Online
Message [ ]Remember the JSX names: className, htmlFor, and style takes an object.
- JSX
- A syntax extension that lets you write markup in JavaScript. It compiles to
jsx()orReact.createElement()calls. - React element
- The plain object a JSX expression produces, like
{ type: "h1", props: {...} }. A description, not a DOM node. - fragment
<>...</>: groups several elements under one root without adding a DOM node.- className / htmlFor
- The JSX names for HTML's
classandfor, because both are reserved words in JavaScript. - dangerouslySetInnerHTML
- The explicit opt-out from React's escaping. Takes
{ __html: string }. Only for trusted or sanitised HTML.