Skip to content

Lesson 2 of 37Thinking in React

JSX

Write JSX confidently, knowing exactly what it compiles to and where it differs from HTML.

13 min read0/4 questions

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.

React
import { createElement } from "react"; export default function App() { const withJsx = <h2 className="title">Made with JSX</h2>; const withoutJsx = createElement("h2", { className: "title" }, "Made with createElement"); console.log(typeof withJsx, withJsx.type); return ( <div> {withJsx} {withoutJsx} </div> );}

Nested JSX becomes nested calls, so a component returns a tree of these objects. React walks that tree to build the page.

What a JSX card compiles into
divjsx("div", { className: "card", children: [...] })h2jsx("h2", { children: "Ada" })pjsx("p", { className: "role", children: "Engineer" })buttonjsx("button", { onClick: f, children: "Follow" })root

The outer <div className="card"> becomes one call whose children prop is an array of the inner elements.

1/3

Because JSX is just values, you can store it in variables, return it from functions, put it in arrays and pass it as arguments.

Quick check
What does <p>Hi</p> evaluate to in a React component?
Need a nudge? A hint rules out a wrong answer.

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.

React
const user = { first: "Ada", last: "Lovelace", unread: 3 }; function fullName(u: { first: string; last: string }) { return `${u.first} ${u.last}`;} export default function App() { const today = new Date().getFullYear(); return ( <div> <h2>Welcome, {fullName(user)}</h2> <p>You have {user.unread} unread messages ({user.unread * 2} if you count drafts).</p> <p>It is {today}. Status: {user.unread > 0 ? "busy" : "all clear"}</p> </div> );}

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").

Predict the outputJavaScript

What text does this paragraph show on screen?

const name = "Sam";
const count = 0;
<p>{name}{false}{null}{undefined} has {count} items</p>
Need a nudge? Hints walk you through it.

Attributes: camelCase JavaScript names

Since JSX turns into JavaScript objects, attribute names follow the DOM's JavaScript property names, not HTML's.

HTMLJSXWhy
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}).

React
export default function App() { const accent = "#0a7"; return ( <form> <label htmlFor="email" style={{ display: "block", fontWeight: 600 }}> Email </label> <input id="email" type="text" placeholder="ada@example.com" aria-label="Email" /> <p className="hint" style={{ color: accent, fontSize: 13, marginTop: 4 }}> We never share it. </p> </form> );}
Quick checkPick all that apply
Which of these JSX attributes are written correctly? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

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, a return followed by a newline returns undefined (automatic semicolon insertion).
Put it in order4 steps

Put the journey of a JSX tag in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

React
const fromUser = "<b>bold?</b> <i>italic?</i>"; export default function App() { return ( <div> <p>Escaped: {fromUser}</p> <p dangerouslySetInnerHTML={{ __html: "Injected: " + fromUser }} /> </div> );}
ChallengeEasy

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 class card.
  • An <h2> with the user's name.
  • A <p> with the class role showing the role in uppercase (use an expression in braces).
  • A <span> with the class status, whose text is Online if user.online is true and Offline otherwise, and whose inline style sets color to green when online and gray when offline.
  • A <label> reading Message that is connected to an <input type="text"> with id="msg".
Ada
ENGINEER
Online
Message [          ]

Remember the JSX names: className, htmlFor, and style takes an object.

React
const user = { name: "Ada", role: "Engineer", online: true }; export default function App() { // Build the card here. return <div></div>;}
Key terms
JSX
A syntax extension that lets you write markup in JavaScript. It compiles to jsx() or React.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 class and for, 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.