JSX
JavaScript XML — expressions, attributes, fragments, and the rules of JSX
Skills taught: react.jsx-syntax, react.expressions, react.attributes, react.fragments, react.jsx-rules
JSX rules and expressions
// JSX looks like HTML but compiles to JavaScript
// Rule 1: one root element (or use a Fragment)
function App() {
const name = 'Alice';
const score = 95;
const isAdmin = true;
return (
<> {/* Fragment — renders nothing to the DOM */}
<h1>Hello, {name}!</h1> {/* expression: JS variable */}
<p>Score: {score * 2}</p> {/* expression: computation */}
<p>Role: {isAdmin ? 'Admin' : 'User'}</p> {/* ternary */}
{/* Render based on condition — false/null/undefined renders nothing */}
{isAdmin && <span>⭐ Admin badge</span>}
</>
);
}
// Rule 2: HTML attributes use camelCase in JSX
function StyledCard({ title, active }) {
return (
<div
className={active ? 'card card-active' : 'card'} {/* class → className */}
style={{ padding: '16px', borderRadius: '8px', background: active ? '#dbeafe' : '#f3f4f6' }}
// style takes an OBJECT, not a string
>
<h2>{title}</h2>
<button onClick={() => console.log('clicked!')}> {/* camelCase event */}
Click me
</button>
<label htmlFor="name-input">Name:</label> {/* for → htmlFor */}
<input id="name-input" type="text" />
</div>
);
}
// Rule 3: all tags must be self-closed or closed
// <br> is wrong — use <br /> or <br></br>
// <input> is wrong — use <input />
function App() {
return (
<>
<StyledCard title="Active" active={true} />
<StyledCard title="Inactive" active={false} />
</>
);
}
Warning: JSX pitfalls: use `className` not `class`, `htmlFor` not `for`, and `style={{color:'red'}}` (object) not `style="color:red"` (string). All tags must be closed — `` not ``.
Frequently Asked Questions
Can I write if/else inside JSX?
Not directly — JSX only accepts expressions, not statements. Instead use: ternary (condition ? A : B), short-circuit (&& for 'render if true'), or move the logic above the return statement. You can also extract complex conditionals into a helper function that returns JSX.