React Lesson 3: JSX — HTML in JavaScript
JSX (JavaScript XML) is the special syntax React uses that looks like HTML but is actually JavaScript. Under the hood, JSX transforms into regular JavaScript function calls.
JSX Rules
// 1. Must return a single root element
// ❌ WRONG:
return (
<h1>Hello</h1>
<p>World</p>
);
// ✅ CORRECT: wrap in a div or Fragment
return (
<div>
<h1>Hello</h1>
<p>World</p>
</div>
);
// ✅ Fragment (no extra DOM element)
return (
<>
<h1>Hello</h1>
<p>World</p>
</>
);
JavaScript Inside JSX — Use {}
const name = "Alice";
const age = 30;
const isLoggedIn = true;
return (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>2 + 2 = {2 + 2}</p>
<p>{isLoggedIn ? "Logged in" : "Please log in"}</p>
<p>{name.toUpperCase()}</p>
</div>
);
className (not class)
// In JSX, use className instead of class
// "class" is a reserved keyword in JavaScript
return (
<div className="container">
<h1 className="title">Hello</h1>
<button className="btn btn-primary">Click</button>
</div>
);
Inline Styles
// Inline styles use double curly braces {{ }}
// Properties are camelCase (not kebab-case)
return (
<div style={{
backgroundColor: "#1a1a2e",
padding: "20px",
borderRadius: "8px",
color: "white"
}}>
<h1 style={{ fontSize: "32px", fontWeight: 700 }}>
Styled Heading
</h1>
</div>
);
Expressions vs Statements
// ✅ Expressions work in JSX:
// {variable}, {function()}, {2+2}, {ternary ? a : b}, {array.map()}
// ❌ Statements do NOT work directly:
// {if (x) { return y; }} — WRONG
// ✅ Use ternary instead:
// {x ? y : null}
🏋️ Practice Task
Create a UserCard component. It should display: name, age, job title, and an “active” badge if the user is active. Style it with inline styles. Use variables for the data, not hardcoded values.
💡 Hint: const user = {name:”Alice”, age:30, job:”Developer”, active:true}. Return JSX with these values inside {}. For badge: {user.active && Active}