JSX Deep Dive
beginnerPart of React Fundamentals
Theory
JSX is a syntax extension that combines JavaScript and HTML-like markup. It gets transpiled to React.createElement() calls by tools like Babel.
Syntax Rules
- JSX must have a single root element (use
<Fragment>or<>...</>) - Self-closing tags:
<img />,<input /> - Use
classNameinstead ofclass,htmlForinstead offor - Attributes are camelCase:
onClick,onChange
Expressions
Embed any JavaScript expression with single curly braces {}. This includes variables, function calls, ternary operators, and array methods. Statements (if, for, switch) are not allowed directly in JSX.
Conditional Rendering
Use ternary operators, logical AND (&&), or IIFEs to conditionally render elements:
{isLoggedIn ? <Dashboard /> : <Login />}
{showWarning && <Warning />}Lists and Keys
When rendering arrays with map(), each element needs a unique key prop. Keys help React identify which items changed, were added, or removed.
Practical Examples
Exercises
Render a Filtered List
Create a component that has an array of product objects (name, price, inStock). Render only the products that are in stock using filter() and map(). Use keys and conditional rendering.
Expected Output:
A list showing only Laptop and Tablet