Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 3 of 10
JSX Deep Dive
JSX looks like HTML but it's pure JavaScript. Understanding exactly what JSX compiles to - and the rules that flow from that - lets you write more expressive components and debug rendering issues with confidence.
What JSX Actually Is
// JSX is SYNTACTIC SUGAR for React.createElement() calls
// The JSX you write:
const element = <h1 className="title">Hello</h1>;
// ...compiles to (via Babel / esbuild):
const element = React.createElement("h1", { className: "title" }, "Hello");
// A more complex example:
const card = (
<div className="card">
<h2>{title}</h2>
<p>{body}</p>
</div>
);
// Compiles to:
const card = React.createElement(
"div",
{ className: "card" },
React.createElement("h2", null, title),
React.createElement("p", null, body)
);
// With the NEW JSX transform (React 17+), you don't need to import React:
// The compiler auto-imports { jsx } from 'react/jsx-runtime'
// This is why modern Vite/Next.js projects don't have 'import React' at the topJSX Rules That Follow From the Compilation
- Single root element: `React.createElement()` returns ONE element - wrap siblings in `<>...</>` (Fragment) to avoid extra DOM nodes
- Expressions only in `{}`: you can use any JS EXPRESSION (values, ternary, function calls) - NOT statements (no `if`, `for`, `while` inside JSX directly)
- camelCase attributes: HTML attributes become JS property names - `class` โ `className`, `for` โ `htmlFor`, `tabindex` โ `tabIndex`
- Self-closing required: JSX runs through an XML parser - `<img>` must be `<img />`, `<input>` must be `<input />`
- String literals vs expressions: `<div className="active">` is a string; `<div style={{ color: 'red' }}>` is a JS object (note double braces: outer = JSX expression, inner = object literal)
- Component names must be capitalized: `<div>` โ HTML element; `<Button>` โ React component (lowercase = string โ HTML tag lookup)
Advanced JSX Patterns
// 1. Dynamic component types (must be capitalized variable)
type HeadingLevel = 'h1' | 'h2' | 'h3';
function Heading({ level, children }: { level: HeadingLevel; children: React.ReactNode }) {
const Tag = level; // uppercase variable โ treated as component
return <Tag className="heading">{children}</Tag>;
}
<Heading level="h2">Section Title</Heading>
// 2. Spread props pattern - forward all props to underlying element
function Button({ className, ...rest }: React.ButtonHTMLAttributes<HTMLButtonElement>) {
return <button className={`btn ${className ?? ''}`} {...rest} />;
}
// 3. Fragments with keys (when mapping)
function DefinitionList({ items }: { items: { term: string; def: string }[] }) {
return (
<dl>
{items.map((item) => (
<React.Fragment key={item.term}>
<dt>{item.term}</dt>
<dd>{item.def}</dd>
</React.Fragment>
// Can't use <> shorthand here - shorthand doesn't accept key prop
))}
</dl>
);
}
// 4. Conditional rendering patterns
function StatusBadge({ status }: { status: 'active' | 'inactive' | 'pending' }) {
// โ
Ternary - for two branches
return status === 'active' ? <span className="green">Active</span> : <span className="grey">Inactive</span>;
}
function Notification({ count }: { count: number }) {
// โ
&& - for optional rendering (careful: avoid 0 && ...)
return <>{count > 0 && <span className="badge">{count}</span>}</>;
// โ WRONG: {count && <span>} - when count=0, renders "0" to the DOM
// โ
CORRECT: {count > 0 && <span>} - explicit boolean comparison
}
// 5. Inline style - must be an object with camelCase keys
const divStyle = { backgroundColor: '#f0f0f0', fontSize: '16px' };
<div style={divStyle}>Styled div</div>Common Mistakes - JSX
- `{count && <Component />}` when count can be 0 - renders the number `0` in the UI; always use `{count > 0 && <Component />}` or `{!!count && ...}`
- Putting JSX in an `if` statement inside the return - JSX inside `return()` must be expressions; hoist the conditional logic above the return
- Forgetting `key` when mapping arrays - React uses keys to identify which items changed; missing keys cause incorrect DOM updates and performance issues
- Using inline object literals for `style` on every render - `style={{ color: 'red' }}` creates a NEW object every render, invalidating memoization; extract to a constant
- Nesting ternaries deeper than 2 levels - extract complex conditions to a named variable or separate component for readability
Tip
Tip
Practice JSX Deep Dive in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for JSX Deep Dive
Practice Task
Note
Practice Task - (1) Write a working example of JSX Deep Dive from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with JSX Deep Dive is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- JSX looks like HTML but it's pure JavaScript.
- Single root element: `React.createElement()` returns ONE element - wrap siblings in `<>...</>` (Fragment) to avoid extra DOM nodes
- Expressions only in `{}`: you can use any JS EXPRESSION (values, ternary, function calls) - NOT statements (no `if`, `for`, `while` inside JSX directly)
- camelCase attributes: HTML attributes become JS property names - `class` โ `className`, `for` โ `htmlFor`, `tabindex` โ `tabIndex`
Finished this lesson?