📖 Notes
LESSON 3 OF 18
JSX — JavaScript + HTML Rules
HTML and JavaScript in the Same File
JSX looks like HTML but compiles to JavaScript function calls — which is exactly why it has its own small set of rules that differ from writing plain HTML.
The 7 Rules
JSX Syntax Rules
1️⃣
One Parent Element
Return one parent element, or use a Fragment <>...</>.
2️⃣
className
Use className instead of class ("class" is reserved in JS).
3️⃣
Self-Closing Tags
Empty tags must self-close: <img />, <br />.
4️⃣
Curly Braces
JavaScript expressions go inside { }.
5️⃣
camelCase Events
onClick, onChange — not onclick, onchange.
6️⃣
Double-Brace Style
style={{ color: "red" }} — an object inside an expression.
⚠️
Rule 7 — the key prop
Arrays of elements need a unique "key" prop:
.map(x => <div key={x.id}>) — React uses it to track which items changed, were added, or removed.All Rules in One Component
JSXfunction Profile({ name, age, isAdmin }) {
return (
<div className="profile">
{/* Conditional rendering */}
{isAdmin && <span>Admin</span>}
{age >= 18 ? <span>Adult</span> : <span>Minor</span>}
{/* Dynamic style */}
<h2 style={{ color: isAdmin ? "gold" : "white" }}>
{name}
</h2>
{/* Lists */}
{["Python","React"].map((skill, i) => (
<span key={i}>{skill}</span>
))}
</div>
);
}