What is JSX?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that lets you write HTML-like markup directly inside a JavaScript file. JSX is not valid JavaScript โ it is transformed into React.createElement() calls by your build tool (Vite / Babel) at compile time.
// What you write
const element = <h1 className="title">Hello, {name}!</h1>;
// What it compiles to (you never write this)
const element = React.createElement(
"h1",
{ className: "title" },
"Hello, ", name, "!"
);
JSX Rules
1. Return a single root element
// โ Two siblings at root โ error!
return (
<h1>Title</h1>
<p>Paragraph</p>
);
// โ
Wrap in a fragment
return (
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
);
2. Close all tags
// โ HTML allows <br> โ JSX does not
<br>
// โ
JSX requires self-closing
<br />
<img src="logo.png" alt="Logo" />
<input type="text" />
3. Use camelCase attributes
// HTML โ JSX
// class โ className
// for โ htmlFor
// tabindex โ tabIndex
// onclick โ onClick
// stroke-width โ strokeWidth
<label htmlFor="email" className="label">Email</label>
<input id="email" className="input" tabIndex={0} />
4. Expressions go inside { }
const name = "Alice";
const isAdmin = true;
const items = ["Apple", "Banana", "Cherry"];
return (
<div>
<p>{name.toUpperCase()}</p> {/* string expression */}
<p>{2 + 2}</p> {/* number expression */}
<p>{isAdmin ? "Admin" : "User"}</p> {/* ternary */}
<p>{isAdmin && <span>โญ</span>}</p> {/* short-circuit */}
<ul>{items.map(i => <li key={i}>{i}</li>)}</ul>
</div>
);
WarningYou cannot use
if, for, or while statements directly inside JSX. Use ternary (? :), logical AND (&&), or move the logic above the return statement.