JSX rules
JSX is not HTML. It compiles to plain JavaScript function calls before it runs, and that origin explains all of its rules. These four rules are worth learning now because they are the first errors every React developer hits: a rejected class attribute, a mysterious "Adjacent JSX elements" message. Knowing why each rule exists turns those errors from roadblocks into thirty-second fixes.
Rule 1: one root element. A function returns one value, so a component must return one element. Wrap siblings in a <div>, or in an empty fragment <>...</> when you do not want an extra DOM node:
function Profile() { return ( <> <h2>Amara</h2> <p>Frontend engineer</p> </> ); }
Rule 2: close every tag. HTML tolerates <br> and <img>. JSX does not, write <br /> and <img />.
Rule 3: curly braces embed JavaScript. Inside JSX, {expression} evaluates any JavaScript expression, a variable, a function call, a ternary:
function Price() { const amount = 19.5; return <p>Total: {amount * 2} dollars</p>; }
That renders Total: 39 dollars. Statements like if or for are not expressions, so they cannot go inside braces. Use ternaries or compute values above the return.
Rule 4: camelCase attributes. Because JSX becomes JavaScript, attribute names follow JavaScript rules. class is a reserved word, so JSX uses className. Also onclick becomes onClick and for becomes htmlFor:
<label htmlFor="email" className="field">Email</label>
Code exercise · javascript
Demystify JSX by building the thing it compiles into. JSX like <h1 className="title">Hello, React</h1> becomes a function call that returns a plain object describing the element. Run this tiny version.
Code exercise · javascript
Your turn. You built the element objects, now do react-dom's job: complete render(el) so it turns an element tree back into an HTML string. A string child renders as itself; an element renders as <type>, each child rendered recursively, then </type>.
Quiz
Spot the bug: ```jsx function Alert() { return ( <h2 class="warning">Low battery</h2> ); } ```
Quiz
Why does this component fail to compile? ```jsx function Stats() { return ( <h2>Stats</h2> <p>42 visits</p> ); } ```