JSX
The HTML-like syntax extension that lets you write UI markup directly inside JavaScript - what it compiles to, and its rules.
What it is, in plain English: JSX (JavaScript XML) is a syntax extension that lets you write HTML-like markup directly inside JavaScript code. It is not valid JavaScript on its own — a build tool (Babel, or Vite's built-in transform) compiles JSX into regular React.createElement() function calls before the browser ever sees it. JSX is optional (you can call React.createElement directly) but is the standard way to write React because it reads naturally and closely resembles the resulting UI.
Writing UI markup inside JavaScript
What JSX looks like
function Greeting() {
return <h1>Hello, World!</h1>;
}
// It LOOKS like HTML, but it's not. It's JavaScript.
// A build tool converts <h1>Hello</h1> into:
// React.createElement("h1", null, "Hello")
// before your browser ever runs the code.Embedding JavaScript values with curly braces
function Greeting({ name }) {
const hour = new Date().getHours();
const greeting = hour < 12 ? "Good morning" : "Good evening";
return (
<div>
<h1>{greeting}, {name}!</h1>
<p>The time is {hour}:00</p>
<p>2 + 2 = {2 + 2}</p>
</div>
);
}
// Anything inside { } is evaluated as a JavaScript expression.JSX's key rules (different from HTML)
// 1. className instead of class (class is a reserved JS word):
<div className="card">...</div>
// 2. Self-closing tags REQUIRE the slash:
<img src="photo.jpg" /> {/* ✓ correct */}
{/* <img src="photo.jpg"> ✗ error in JSX */}
<br />
<input type="text" />
// 3. Must return exactly ONE root element:
// ✗ This is invalid:
// return (<h1>Title</h1><p>Text</p>);
// ✓ Wrap in a single parent:
return (
<div>
<h1>Title</h1>
<p>Text</p>
</div>
);
// 4. camelCase for attributes (onclick → onClick, tabindex → tabIndex):
<button onClick={handleClick}>Click</button>Fragments — a root wrapper without adding a DOM element
// Sometimes you don't want an extra <div> wrapping your content:
function Pair() {
return (
<>
<td>Cell 1</td>
<td>Cell 2</td>
</>
);
}
// <>...</> is shorthand for <React.Fragment>...</React.Fragment>
// Renders the children with NO extra wrapping element in the DOM
Try It Yourself (JSX)
Official Sources
- React Documentation — Writing Markup with JSX
- React Documentation — JavaScript in JSX with Curly Braces
- React Documentation — Conditional Rendering
- Babel — JSX Handbook
The Codex links only to official documentation. No third-party tutorials.