JSX Syntax
JSX is a syntax extension for JavaScript that looks like HTML. React uses it to describe what the UI should look like.
Embedding Expressions
Wrap any JavaScript expression in curly braces {}:
const name = "Alice";
const element = <h1>Hello, {name}!</h1>;
You can use any expression — variables, function calls, ternaries, math.
Self-Closing Tags
Every tag must be closed. HTML-style self-closing works:
const img = <img src="photo.jpg" alt="Photo" />;
const input = <input type="text" />;
Forgetting the / is a common syntax error.
Fragments
Return multiple elements without an extra wrapper:
function List() {
return (
<>
<li>One</li>
<li>Two</li>
</>
);
}
<> is shorthand for <React.Fragment>. No extra DOM nodes are created.
JSX is Not HTML
JSX uses camelCase for attributes:
// HTML JSX
class="box" → className="box"
for="email" → htmlFor="email"
onclick={handler} → onClick={handler}
tabindex="0" → tabIndex="0"
Style values are objects, not strings:
<div style={{ color: "red", fontSize: "16px" }}>Red text</div>
Returning JSX
A component must return a single root element:
function Card() {
return (
<div>
<h2>Title</h2>
<p>Body</p>
</div>
);
}
Use a fragment if you don’t need a wrapper div.
Best Practices
- Use fragments — Avoid unnecessary divs in the DOM
- Keep JSX readable — Break into multiple lines for complex elements
- Use className and htmlFor — Not
classandfor - Self-close empty tags —
<img />,<input />,<br />
Common Mistakes
- Forgetting return parentheses — Multi-line JSX needs
()afterreturn - Using
classinstead ofclassName— JSX uses camelCase - Returning multiple root elements — Wrap in a fragment or div
- Using quotes for dynamic values — Use
{}for JavaScript expressions