Components and JSX
The basic JSX rules
Close tags, return one root, and use React property names where JSX differs from HTML.
JSX is stricter than HTML in a few useful ways. The strictness is not pedantry: JSX compiles to JavaScript, and JavaScript cannot tolerate the ambiguity browsers forgive in HTML. Learn these rules once and the error messages start making sense.
Every tag must close. HTML lets you write <img> or <input> bare; JSX does not:
<img src="/avatar.jpg" alt="Ada" />
<input name="email" type="email" />
The self-closing /> is mandatory for elements without children. Leave it off and the compiler stops with an unterminated-tag error instead of guessing what you meant.
A component returns one root value, because a return statement can only return one thing. Use a meaningful parent when the DOM needs one, or a fragment when it does not:
return (
<>
<Header />
<main>{content}</main>
</>
)
If you forget, the error reads “Adjacent JSX elements must be wrapped in an enclosing tag”. That message means exactly this rule: two siblings at the top of a return need a shared parent.
Most properties use DOM-oriented JavaScript names. Use className for CSS classes and camelCase for events such as onClick and onChange. The names come from the DOM’s JavaScript API rather than from HTML attribute spelling.
Accessibility and data attributes keep their HTML spelling:
<button aria-label="Close" data-action="dismiss">×</button>
Use htmlFor on a label because for has another meaning in JavaScript:
<label htmlFor="email">Email</label>
<input id="email" name="email" />
The realistic failure is quiet, not loud. Write class instead of className and the page still renders, but React logs a warning and your CSS may not apply. React reports many invalid properties in the console. Read the warning instead of guessing; it usually names the property and the correction.
Convert a small HTML form to JSX. Check closing tags, className, htmlFor, and the single returned root. Then inspect the output DOM to confirm it remains semantic HTML: the JSX rules are for the compiler, and the browser still receives ordinary elements.
Lesson completed