Chapter 03 - Laying the Foundation

Chapter 03 - Laying the Foundation

Hey everyone! Welcome back to Namaste React!

We have set up our development environment with Parcel in the last chapter. Now it's time to actually understand what React is made of. Today we learn the stuff you write every single day as a React developer — JSX, Components, and Props!

By the end of this chapter, you will understand not just HOW to write JSX, but WHY it looks the way it does and what the browser actually receives. Let's go deep!

What we will cover:

  • What is JSX? Why does it exist?
  • JSX is NOT HTML — the differences
  • What is Babel? How it transpiles JSX
  • JSX expressions — rules and gotchas
  • Functional Components — defining and calling them
  • Component Composition — components inside components
  • React Fragment — <></> and why we need it
  • Props — passing data into components
  • Props destructuring and default props
  • Rendering lists with .map() and the key prop
  • Conditional rendering — &&, ternary, if/else
  • React DevTools — inspecting your component tree
  • Interview Questions

1. What is JSX? Why Does It Exist?

In the last chapter, we wrote React.createElement() calls that looked like this:

// The React way WITHOUT JSX (what we did in Chapter 01)
const heading = React.createElement(
    "div",
    { id: "parent" },
    React.createElement(
        "div",
        { id: "child" },
        React.createElement("h1", {}, "Hello World from React!")
    )
);

Imagine writing an entire web application like that. A single page with a header, sidebar, footer, cards, buttons, forms — hundreds of nested createElement() calls. It would be unreadable and unmaintainable!

JSX was invented to solve this.

┌─────────────────────────────────────────────────────────────┐
│                       WHAT IS JSX?                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  JSX = JavaScript XML                                       │
│                                                             │
│  It is a SYNTAX EXTENSION for JavaScript that lets you      │
│  write HTML-like code inside JavaScript.                    │
│                                                             │
│  JSX is NOT a new language — it's just a shorter way        │
│  to write React.createElement() calls!                      │
│                                                             │
│  WITHOUT JSX (Chapter 01 style):                            │
│  ════════════════════════════════                            │
│  React.createElement("h1", {id: "title"}, "Hello World")   │
│                                                             │
│  WITH JSX (What you write every day):                       │
│  ════════════════════════════════════                        │
│  <h1 id="title">Hello World</h1>                           │
│                                                             │
│  Same result! JSX is just CLEANER to read and write!        │
│                                                             │
└─────────────────────────────────────────────────────────────┘
The same nested structure from Chapter 01, now in JSX:
=======================================================

// WITHOUT JSX (50 lines of createElement calls):
const parent = React.createElement("div", { id: "parent" },
    React.createElement("div", { id: "child1" },
        React.createElement("h1", {}, "I am h1"),
        React.createElement("h2", {}, "I am h2")
    ),
    React.createElement("div", { id: "child2" },
        React.createElement("h1", {}, "I am h1"),
        React.createElement("h2", {}, "I am h2")
    )
);

// WITH JSX (exactly the same, but readable!):
const parent = (
    <div id="parent">
        <div id="child1">
            <h1>I am h1</h1>
            <h2>I am h2</h2>
        </div>
        <div id="child2">
            <h1>I am h1</h1>
            <h2>I am h2</h2>
        </div>
    </div>
);

SAME OUTPUT. JSX is purely for developer convenience!

Important: Browsers do NOT understand JSX. Browsers only understand JavaScript. So something has to convert JSX into JavaScript before the browser sees it. That something is Babel!


2. JSX is NOT HTML — Key Differences

This is one of the most common sources of confusion for beginners. JSX looks like HTML but it is NOT HTML. Here are the differences you MUST know:

┌─────────────────────────────────────────────────────────────┐
│                JSX vs HTML — DIFFERENCES                    │
└─────────────────────────────────────────────────────────────┘


DIFFERENCE 1: className instead of class
══════════════════════════════════════════

// ❌ HTML way (doesn't work in JSX!)
<div class="container">Hello</div>

// ✅ JSX way (always use className!)
<div className="container">Hello</div>

WHY? Because 'class' is a RESERVED keyword in JavaScript!
(Used for class MyComponent extends React.Component)
JSX compiles to JavaScript, so reserved words can't be used as attributes.


DIFFERENCE 2: htmlFor instead of for
══════════════════════════════════════

// ❌ HTML way
<label for="email">Email:</label>

// ✅ JSX way
<label htmlFor="email">Email:</label>

WHY? 'for' is also a reserved keyword in JavaScript! (for loops)


DIFFERENCE 3: camelCase for all attributes
═══════════════════════════════════════════

// HTML uses lowercase hyphenated:
<div onclick="handleClick()" tabindex="1" maxlength="10">

// JSX uses camelCase:
<div onClick={handleClick} tabIndex={1} maxLength={10}>

More examples:
HTML attribute   →   JSX attribute
───────────────────────────────────
onclick          →   onClick
onchange         →   onChange
onkeydown        →   onKeyDown
onmouseenter     →   onMouseEnter
tabindex         →   tabIndex
maxlength        →   maxLength
readonly         →   readOnly
autocomplete     →   autoComplete
autofocus        →   autoFocus
crossorigin      →   crossOrigin
enctype          →   encType


DIFFERENCE 4: Self-closing tags are REQUIRED
══════════════════════════════════════════════

// ❌ HTML allows this (lazy closing):
<img src="photo.jpg">
<input type="text">
<br>
<hr>

// ✅ JSX REQUIRES self-closing slash:
<img src="photo.jpg" />
<input type="text" />
<br />
<hr />

WHY? JSX is stricter — it must be valid XML (hence the name JavaScript XML)


DIFFERENCE 5: style is an OBJECT, not a string
════════════════════════════════════════════════

// ❌ HTML way (inline styles as string):
<div style="color: red; font-size: 16px;">

// ✅ JSX way (inline styles as JavaScript OBJECT):
<div style={{ color: "red", fontSize: "16px" }}>

Notice TWO curly braces {{ }}:
  Outer { } = "I'm writing JavaScript in JSX"
  Inner { } = "This is a JavaScript object"

Also notice:
  CSS: font-size    →   JSX: fontSize   (camelCase!)
  CSS: background-color → JSX: backgroundColor
  CSS: border-radius    → JSX: borderRadius
  CSS: z-index          → JSX: zIndex


DIFFERENCE 6: Comments are different
═══════════════════════════════════════

// HTML comments:
<!-- This is an HTML comment -->

// JSX comments (inside JSX, must use {}):
{/* This is a JSX comment */}

// Or outside JSX, regular JS comments work:
// This is a comment
/* This is also a comment */

3. What is Babel? How It Transpiles JSX

┌─────────────────────────────────────────────────────────────┐
│                       WHAT IS BABEL?                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Babel is a JavaScript COMPILER (or transpiler).            │
│                                                             │
│  It converts:                                               │
│  - Modern JavaScript (ES6, ES7, ES8...) → older JavaScript  │
│  - JSX → React.createElement() calls                        │
│  - TypeScript → plain JavaScript                            │
│                                                             │
│  WHY?                                                       │
│  Not all browsers support the latest JavaScript features.   │
│  Babel converts your modern code into code that works       │
│  in older browsers too!                                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘
HOW BABEL TRANSPILES JSX:
===========================

Your JSX Code (what you write):
────────────────────────────────
const heading = <h1 className="title">Hello World!</h1>;

After Babel transforms it (what the browser sees):
────────────────────────────────────────────────────
// OLD Transform (React 16 and before):
const heading = React.createElement(
    "h1",
    { className: "title" },
    "Hello World!"
);

// NEW Transform (React 17+ with new JSX transform):
import { jsx as _jsx } from "react/jsx-runtime";
const heading = _jsx("h1", {
    className: "title",
    children: "Hello World!"
});

Both produce the SAME result. The new transform is slightly
more efficient and doesn't require importing React at the top
of every file. That's why in React 17+, you don't need:
import React from "react";  ← No longer required!

But in React 16 and below:
import React from "react";  ← REQUIRED! (Babel needed React in scope)
BABEL IN YOUR PARCEL SETUP:
=============================

When you run: npx parcel index.html

Parcel automatically:
1. Detects .jsx / .js files with JSX
2. Uses Babel under the hood to transform JSX
3. You get compiled JavaScript the browser understands!

You never manually run Babel — Parcel handles it for you!

Your Flow:
  You write JSX  →  Parcel  →  Babel transforms  →  Bundle  →  Browser runs it

Zero config! Parcel automatically knows how to handle JSX!


WHAT IF YOU USE VITE?
======================
// vite.config.js — Vite uses esbuild (not Babel) for JSX by default
// But you can add Babel if needed

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";  // Uses Babel

export default defineConfig({
    plugins: [react()]
});

Quick test your understanding: Open the browser DevTools on a React app, go to Sources, and look for your .js files. You'll see the compiled JavaScript that Babel produced — no JSX! That's what the browser actually runs.


4. JSX Expressions — Rules and Gotchas

RULE 1: Use { } to embed JavaScript expressions in JSX
=========================================================

const name = "Akshay";
const age = 25;

// Single {} means: "run this JavaScript expression and render the result"
const element = (
    <div>
        <p>Name: {name}</p>        // Renders: "Name: Akshay"
        <p>Age: {age}</p>          // Renders: "Age: 25"
        <p>Next year: {age + 1}</p> // Renders: "Next year: 26"
        <p>Upper: {name.toUpperCase()}</p> // Renders: "Upper: AKSHAY"
    </div>
);

// You can put ANY JavaScript EXPRESSION inside { }:
// ✅ Variables
// ✅ Arithmetic: {2 + 2}
// ✅ Ternary: {isLoggedIn ? "Welcome!" : "Please login"}
// ✅ Function calls: {formatDate(date)}
// ✅ Array methods: {items.map(...)}
// ✅ Template literals: {`Hello ${name}`}

// ❌ But NOT statements:
// ❌ {if (x) { }}      — if is a statement, not an expression
// ❌ {for (;;) { }}    — for loop is a statement
// ❌ {let x = 5}       — variable declaration is a statement
RULE 2: JSX must have ONE root element
========================================

// ❌ WRONG — two root elements (JSX error!)
const element = (
    <h1>Hello</h1>
    <p>World</p>
);

// ✅ CORRECT — wrap in a single root div
const element = (
    <div>
        <h1>Hello</h1>
        <p>World</p>
    </div>
);

WHY? Remember, JSX compiles to React.createElement().
     A function can only return ONE value!
     React.createElement() can only return ONE element.
     Two root elements would mean two return values — not valid!


The PROBLEM with wrapping everything in divs:
══════════════════════════════════════════════

// If every component adds a wrapper div:
<div>           ← App's div
    <div>       ← Header's div
        <div>   ← Nav's div
            ...
        </div>
    </div>
    <div>       ← Main's div
        <div>   ← Card's div
            ...
        </div>
    </div>
</div>

Too many wrapper divs = "div soup"!
This messes up CSS flexbox/grid layouts and accessibility.
→ Solution: React.Fragment!
RULE 3: JSX expressions are evaluated, not printed
====================================================

const x = 10;

// ✅ These WORK (render a value)
{x}                    // Renders: 10
{x + 5}               // Renders: 15
{x > 5 ? "Yes" : "No"} // Renders: Yes
{"Hello"}              // Renders: Hello
{true}                 // Renders: NOTHING (booleans don't render!)
{null}                 // Renders: NOTHING
{undefined}            // Renders: NOTHING

// ⚠️ Gotcha — NUMBERS render, but 0 renders as "0"!
{0}                    // Renders: 0 (number zero!)
{0 && <Component />}   // Renders: 0 (NOT nothing!)

// The 0 gotcha in conditional rendering:
const count = 0;
// ❌ Shows "0" on screen!
{count && <p>Items: {count}</p>}

// ✅ Correct — use ternary or explicit boolean
{count > 0 && <p>Items: {count}</p>}
{Boolean(count) && <p>Items: {count}</p>}
{count ? <p>Items: {count}</p> : null}

5. Functional Components — The Modern Way

In React, a Component is a reusable, independent piece of your UI. Think of it as a custom HTML tag that you define yourself!

┌─────────────────────────────────────────────────────────────┐
│               WHAT IS A COMPONENT?                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  A component is a JavaScript FUNCTION that:                 │
│  1. Takes props (optional) as input                         │
│  2. Returns JSX as output                                   │
│                                                             │
│  Just like a function:                                      │
│  Input → Process → Output                                   │
│  Props → Component → JSX (what to display)                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘
DEFINING A FUNCTIONAL COMPONENT:
==================================

// Method 1: Function declaration
function Heading() {
    return <h1>Hello from Heading Component!</h1>;
}

// Method 2: Arrow function (more common in modern React)
const Heading = () => {
    return <h1>Hello from Heading Component!</h1>;
};

// Method 3: Arrow function with implicit return
const Heading = () => <h1>Hello from Heading Component!</h1>;

// Method 4: Arrow function with parentheses (multi-line JSX)
const Heading = () => (
    <div>
        <h1>Hello from Heading Component!</h1>
        <p>I am a paragraph inside heading component</p>
    </div>
);

All four are valid. Arrow functions are more common in modern React.
THE NAMING RULE — CAPITAL LETTER REQUIRED!
===========================================

// ✅ Component name MUST start with a Capital letter
function MyComponent() { ... }
const UserCard = () => { ... }
const App = () => { ... }

// ❌ Lowercase = treated as HTML tag, NOT a component!
function myComponent() { ... }    // ❌ React won't treat as component
const app = () => { ... }         // ❌ Same issue

WHY? React uses the first letter to tell the difference:
  Lowercase → <div>, <h1>, <input> → HTML tag → React.createElement("div", ...)
  Capital   → <MyComponent /> → Component → React.createElement(MyComponent, ...)

The first letter IS the signal to React!
CALLING / USING A COMPONENT:
==============================

// After defining:
function Heading() {
    return <h1>Hello!</h1>;
}

// Use it like a custom HTML tag:
const element = <Heading />;

// Or with children:
// (We'll see this more when we get to props)


// RENDERING THE ROOT COMPONENT:
import React from "react";
import ReactDOM from "react-dom/client";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);   // App is the root component — renders everything!


// COMPONENT vs REACT ELEMENT:
const HeadingComponent = () => <h1>Hello!</h1>;  // COMPONENT (function)
const headingElement = <HeadingComponent />;         // ELEMENT (using the component)
const headingElement2 = HeadingComponent();          // Also valid (direct call, but avoid!)

// Always prefer <ComponentName /> over ComponentName()
// React needs to treat it as an element to manage lifecycle, hooks, etc.

6. Component Composition — Components Inside Components

Component Composition is the technique of combining small components to build larger ones. This is the HEART of React!

BUILDING A PAGE FROM SMALL COMPONENTS:
========================================

// Small reusable components:
const Logo = () => <img src="/logo.png" alt="Logo" />;

const SearchBar = () => (
    <input type="text" placeholder="Search restaurants..." />
);

const UserIcon = () => <div className="user-icon">👤</div>;

// Composed into Header:
const Header = () => (
    <header className="header">
        <Logo />
        <SearchBar />
        <UserIcon />
    </header>
);

// And Header is used inside App:
const App = () => (
    <div>
        <Header />
        <main>
            <p>Main content here</p>
        </main>
    </div>
);
THE COMPONENT TREE:
====================

         <App>
        /       \
  <Header>    <main>
  /   |   \
<Logo> <SearchBar> <UserIcon>

This tree structure is EXACTLY what React manages as the Fiber tree!
(Remember this from Deep Dive 01!)

Benefits of Composition:
✅ Each component has ONE responsibility
✅ Easy to test in isolation
✅ Reuse components anywhere in the app
✅ Easy to reason about (just look at component = see what it does)
✅ Small changes don't break unrelated parts
// Real-world example — a restaurant card:
const RestaurantCard = () => (
    <div className="res-card">
        <img
            className="res-logo"
            src="https://media.swiggy.com/..."
            alt="Burger Palace"
        />
        <h3>Burger Palace</h3>
        <h4>Burgers, Fast Food</h4>
        <h4>4.2 stars</h4>
        <h4>30-40 mins</h4>
    </div>
);

// Used inside the Body component:
const Body = () => (
    <div className="body">
        <RestaurantCard />
        <RestaurantCard />
        <RestaurantCard />
    </div>
);

// But wait — all three cards show the SAME data!
// We need to pass DIFFERENT data to each card.
// That's where PROPS come in! (Section 8)

7. React Fragment — <></> Why We Need It

THE PROBLEM — Unnecessary wrapper divs:
=========================================

// You need to return two elements, so you wrap in a div:
function UserInfo() {
    return (
        <div>              {/* ← Unnecessary wrapper! */}
            <h1>John Doe</h1>
            <p>Software Engineer</p>
        </div>
    );
}

// This adds an extra <div> to the real DOM.
// In a complex app, you get "div soup":
<div><div><div><div><div>...</div></div></div></div></div>
// Breaks flexbox, grid layouts. Bad for accessibility.


THE SOLUTION — React.Fragment:
================================

// Method 1: React.Fragment (explicit)
function UserInfo() {
    return (
        <React.Fragment>
            <h1>John Doe</h1>
            <p>Software Engineer</p>
        </React.Fragment>
    );
}

// Method 2: Short syntax <></> (most common)
function UserInfo() {
    return (
        <>
            <h1>John Doe</h1>
            <p>Software Engineer</p>
        </>
    );
}

// Both produce the SAME output:
// <h1>John Doe</h1>
// <p>Software Engineer</p>
// NO wrapper div in the real DOM!
WHEN TO USE React.Fragment vs <></>:
=======================================

Use <></> (short syntax) in MOST cases:
<>
    <Child1 />
    <Child2 />
</>


Use <React.Fragment> when you need to pass the KEY prop:
// Rendering a list where the fragment itself needs a key:
function List({ items }) {
    return items.map(item => (
        <React.Fragment key={item.id}>  {/* ← key only works on React.Fragment! */}
            <dt>{item.term}</dt>
            <dd>{item.description}</dd>
        </React.Fragment>
    ));
}

// ❌ key doesn't work on short syntax:
// <> doesn't accept key prop! Use <React.Fragment key={...}>

8. Props — Passing Data Into Components

Props (short for Properties) are how you pass data from a parent component to a child component. They are the arguments to your component function!

┌─────────────────────────────────────────────────────────────┐
│                  WHAT ARE PROPS?                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Props = Function Arguments for Components                  │
│                                                             │
│  Regular function:                                          │
│  function greet(name) { return "Hello " + name; }          │
│  greet("Akshay");     ← Passing an argument                 │
│                                                             │
│  React component:                                           │
│  function Greet(props) { return <h1>Hello {props.name}</h1> }│
│  <Greet name="Akshay" />  ← Passing a prop                 │
│                                                             │
│  SAME CONCEPT, different syntax!                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘
PASSING PROPS:
===============

// Parent component passes props (like HTML attributes):
const App = () => (
    <div>
        <RestaurantCard
            resName="Burger Palace"
            cuisine="Burgers, Fast Food"
            rating={4.2}
            deliveryTime="30-40 mins"
        />
        <RestaurantCard
            resName="Pizza Paradise"
            cuisine="Pizza, Italian"
            rating={4.5}
            deliveryTime="25-35 mins"
        />
    </div>
);


RECEIVING PROPS:
================

// Child component receives all props as ONE object:
function RestaurantCard(props) {
    console.log(props);
    // {
    //   resName: "Burger Palace",
    //   cuisine: "Burgers, Fast Food",
    //   rating: 4.2,
    //   deliveryTime: "30-40 mins"
    // }

    return (
        <div className="res-card">
            <h3>{props.resName}</h3>
            <h4>{props.cuisine}</h4>
            <h4>Rating: {props.rating} stars</h4>
            <h4>{props.deliveryTime}</h4>
        </div>
    );
}
PROPS DESTRUCTURING — The cleaner way:
========================================

// Instead of props.resName, props.cuisine, etc.
// Destructure props right in the function argument:

function RestaurantCard({ resName, cuisine, rating, deliveryTime }) {
    return (
        <div className="res-card">
            <h3>{resName}</h3>           {/* No props. needed! */}
            <h4>{cuisine}</h4>
            <h4>Rating: {rating} stars</h4>
            <h4>{deliveryTime}</h4>
        </div>
    );
}

// Arrow function version:
const RestaurantCard = ({ resName, cuisine, rating, deliveryTime }) => (
    <div className="res-card">
        <h3>{resName}</h3>
        <h4>{cuisine}</h4>
        <h4>Rating: {rating} stars</h4>
        <h4>{deliveryTime}</h4>
    </div>
);

// This is the PREFERRED style in modern React!
PASSING DIFFERENT TYPES OF PROPS:
===================================

<MyComponent
    // Strings — no {} needed, use quotes:
    name="John"
    title="Developer"

    // Numbers — use {}:
    age={25}
    count={0}

    // Booleans — {} or just the attribute name:
    isActive={true}
    isAdmin            {/* same as isAdmin={true} */}
    isDeleted={false}

    // Objects — use {}:
    style={{ color: "red", fontSize: "16px" }}
    config={{ theme: "dark", lang: "en" }}

    // Arrays — use {}:
    items={[1, 2, 3]}
    colors={["red", "blue", "green"]}

    // Functions — use {}:
    onClick={handleClick}
    onChange={e => setName(e.target.value)}

    // JSX — use {}:
    icon={<svg>...</svg>}
    header={<h1>Title</h1>}

    // Expressions — use {}:
    total={price * quantity}
    label={`Hello ${userName}`}
/>
DEFAULT PROPS — what to show when prop is not passed:
======================================================

// Method 1: Default values in destructuring (recommended)
function Button({ label = "Click Me", color = "blue", size = "medium" }) {
    return (
        <button style={{ color }} className={`btn-${size}`}>
            {label}
        </button>
    );
}

// Usage — some props not passed:
<Button />              // Uses ALL defaults: "Click Me", blue, medium
<Button label="Save" /> // label="Save", rest are defaults
<Button color="red" />  // color="red", rest are defaults


// Method 2: defaultProps (older way, still seen in codebases)
Button.defaultProps = {
    label: "Click Me",
    color: "blue",
    size: "medium"
};

// Method 1 is preferred — more readable, TypeScript-friendly
PROPS ARE READ-ONLY — The One Absolute Rule:
=============================================

// Props flow ONE WAY: Parent → Child
// A child component can NEVER modify its props!

function Child({ name }) {
    // ❌ Never do this! Trying to modify props:
    name = "Modified";      // This would break React's data flow!

    // ✅ If you need to modify it, use STATE (useState)
    // Props are for INPUT, state is for what changes over time
}

WHY? This is called "One-Way Data Flow" or "Unidirectional Data Flow".
It makes apps predictable and easy to debug — you always know
where data is coming FROM (the parent).

If child needs to "change" something in parent → use callbacks!
(Parent passes a function as prop, child calls it)

9. Rendering Lists with .map() and the key Prop

THE SCENARIO — Rendering a list of restaurants:
================================================

const restaurants = [
    { id: 1, name: "Burger Palace", cuisine: "Burgers", rating: 4.2 },
    { id: 2, name: "Pizza Paradise", cuisine: "Pizza", rating: 4.5 },
    { id: 3, name: "Sushi World", cuisine: "Japanese", rating: 4.8 },
    { id: 4, name: "Taco Town", cuisine: "Mexican", rating: 4.1 },
];

// ❌ You can NOT do this (JSX, not a template engine):
// <div>
//   for (let res of restaurants) {
//     <RestaurantCard ... />
//   }
// </div>

// ✅ Use .map() — it returns an ARRAY of JSX elements!
const Body = () => (
    <div className="body">
        {restaurants.map(restaurant => (
            <RestaurantCard
                key={restaurant.id}           // ← KEY IS REQUIRED!
                resName={restaurant.name}
                cuisine={restaurant.cuisine}
                rating={restaurant.rating}
            />
        ))}
    </div>
);
WHY IS THE key PROP REQUIRED?
===============================

React uses keys to track which list items changed between renders.

Without key → React gets a WARNING in the console:
⚠️ Warning: Each child in a list should have a unique "key" prop.


HOW KEY HELPS:
===============

// Initial render:
[
    <Card key="1" name="Burger Palace" />,
    <Card key="2" name="Pizza Paradise" />,
    <Card key="3" name="Sushi World" />
]

// After reorder (user sorts by rating):
[
    <Card key="3" name="Sushi World" />,    // was last, now first
    <Card key="2" name="Pizza Paradise" />, // moved
    <Card key="1" name="Burger Palace" />   // was first, now last
]

WITH KEY: React sees "key 3 just moved" → MOVE the DOM node. (fast!)
WITHOUT KEY: React sees "first position changed" → UPDATE all. (slow!)

// Always use a STABLE, UNIQUE identifier as the key!
// ✅ Database ID: key={restaurant.id}
// ✅ Unique code: key={restaurant.code}
// ❌ Array index: key={index} (breaks when list reorders!)
// ❌ Random:      key={Math.random()} (new key every render = no optimization!)
PASSING THE WHOLE OBJECT AS A PROP (spread operator):
======================================================

// Instead of passing each field individually:
<RestaurantCard
    key={restaurant.id}
    resName={restaurant.name}
    cuisine={restaurant.cuisine}
    rating={restaurant.rating}
/>

// You can spread the whole object:
<RestaurantCard
    key={restaurant.id}
    resData={restaurant}       // pass the whole object
/>

// Then in the component:
const RestaurantCard = ({ resData }) => {
    const { name, cuisine, rating } = resData;
    return (
        <div>
            <h3>{name}</h3>
            <h4>{cuisine}</h4>
            <h4>{rating}⭐</h4>
        </div>
    );
};

// OR use the spread operator to pass all fields:
<RestaurantCard key={restaurant.id} {...restaurant} />
// This is same as: resName={restaurant.resName} cuisine={restaurant.cuisine} ...
// Use with caution — can accidentally pass unneeded props!

10. Conditional Rendering — &&, Ternary, if/else

TECHNIQUE 1: Ternary Operator (most common)
============================================

// Show different UI based on a condition:
const UserGreeting = ({ isLoggedIn }) => (
    <div>
        {isLoggedIn
            ? <h1>Welcome back! 👋</h1>
            : <h1>Please log in.</h1>
        }
    </div>
);

// Usage:
<UserGreeting isLoggedIn={true} />   // Renders: Welcome back! 👋
<UserGreeting isLoggedIn={false} />  // Renders: Please log in.


// Multi-element ternary:
const Component = ({ loading }) => (
    <div>
        {loading
            ? (
                <>
                    <div className="shimmer" />
                    <div className="shimmer" />
                </>
            )
            : (
                <>
                    <Header />
                    <Body />
                </>
            )
        }
    </div>
);
TECHNIQUE 2: && (short-circuit) — show OR show nothing
========================================================

// When you only have ONE case (show this, or show nothing):
const Notification = ({ hasMessages, count }) => (
    <div>
        {/* Only renders the badge if hasMessages is true */}
        {hasMessages && (
            <span className="badge">{count} messages</span>
        )}
        <p>Inbox</p>
    </div>
);

// How && works in JavaScript:
// true  && <span>...</span>  → <span>...</span>  (renders!)
// false && <span>...</span>  → false               (renders nothing)
// null  && <span>...</span>  → null                (renders nothing)


// ⚠️ THE 0 GOTCHA with &&:
// 0 is falsy, so 0 && <Component> evaluates to 0
// 0 renders as "0" on screen!

// ❌ Bug — shows "0" when count is 0:
{count && <Badge count={count} />}

// ✅ Fix — explicit boolean check:
{count > 0 && <Badge count={count} />}
{!!count && <Badge count={count} />}
TECHNIQUE 3: if/else OUTSIDE the return
=========================================

// You can use regular if/else BEFORE the return statement:
const RestaurantCard = ({ resData }) => {
    // ✅ Regular if/else works outside JSX!
    if (!resData) {
        return <div>Restaurant not found!</div>;
    }

    if (resData.isClosed) {
        return <div className="closed">{resData.name} is Closed</div>;
    }

    return (
        <div className="res-card">
            <h3>{resData.name}</h3>
            <p>{resData.cuisine}</p>
        </div>
    );
};

// This is called "early return" and is very common in React!
// Guard clauses at the top, happy path at the bottom.
TECHNIQUE 4: Variable assignment — for complex conditions
==========================================================

const Dashboard = ({ user, loading, error }) => {
    // Build the content based on conditions:
    let content;

    if (loading) {
        content = <Spinner />;
    } else if (error) {
        content = <ErrorMessage message={error} />;
    } else if (!user) {
        content = <EmptyState />;
    } else {
        content = <UserProfile user={user} />;
    }

    // Return with the determined content:
    return (
        <div className="dashboard">
            <Header />
            {content}   {/* render the variable */}
            <Footer />
        </div>
    );
};

// This is cleaner than deeply nested ternaries!


// Summary of when to use which:
// ───────────────────────────────────────────────
// Condition       → Technique
// ───────────────────────────────────────────────
// Show A or B     → Ternary operator
// Show A or nothing → && operator (watch out for 0!)
// Complex logic   → if/else outside return
// Many conditions → Variable assignment
// Early exit      → if (!data) return <div>...</div>

11. React DevTools — Your Best Debugging Friend

WHAT IS REACT DEVTOOLS?
========================

React DevTools is a Chrome/Firefox extension that adds two new
tabs to your browser's Developer Tools:

  ⚛ Components  → Inspect the component tree, props, and state
  ⚛ Profiler    → Measure rendering performance


HOW TO INSTALL:
================

1. Open Chrome Web Store
2. Search "React Developer Tools"
3. Install the extension by Facebook
4. Open your React app in the browser
5. Open DevTools (F12 / Cmd+Option+I)
6. You'll see "Components" and "Profiler" tabs!


WHAT YOU CAN DO WITH COMPONENTS TAB:
======================================

┌─────────────────────────────────────────────────────────────┐
│  ⚛ Components                                               │
│                                                             │
│  ▼ App                                                      │
│    ▼ Header                                                 │
│        Logo                                                 │
│        SearchBar                                            │
│        UserIcon                                             │
│    ▼ Body                                                   │
│        RestaurantCard    ← Click to inspect!                │
│        RestaurantCard                                       │
│        RestaurantCard                                       │
│    Footer                                                   │
│                                                             │
│  Props ──────────────                                       │
│    resName: "Burger Palace"                                 │
│    cuisine: "Burgers, Fast Food"                            │
│    rating: 4.2                                              │
│    deliveryTime: "30-40 mins"                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

You can:
✅ See the entire component tree
✅ Click any component to see its props
✅ See component state (when we learn useState)
✅ Edit props/state LIVE and see changes
✅ Search for a specific component by name
✅ Find what component rendered a specific element ($r trick)
THE $r TRICK:
===============

In Chrome DevTools:
1. Go to Elements tab
2. Click on an HTML element
3. Switch to Components tab
4. DevTools shows you which React component renders that element!

OR in console: type $r
→ This gives you the INSTANCE of the currently selected component
→ $r.props  → see its props
→ $r.state  → see its state
→ Very useful for quick debugging!


PROFILER TAB — Finding slow components:
=========================================

1. Click "Record" in Profiler tab
2. Interact with your app
3. Click "Stop"
4. See which components re-rendered and how long each took

Colored bars:
  Green  → fast render
  Yellow → medium render
  Red    → slow render (needs optimization!)

We'll use this a lot in Chapter 09 when we optimize our app!

Coding — Building a Restaurant Listing Page

// App.js — Full example using everything from this chapter

import React from "react";
import ReactDOM from "react-dom/client";

// Data (will come from API in Chapter 06)
const restaurantData = [
    {
        id: 1,
        name: "Burger Palace",
        cuisine: "Burgers, Fast Food",
        rating: 4.2,
        deliveryTime: "30-40 mins",
        image: "https://media.swiggy.com/burger-palace.jpg",
        isNew: true,
    },
    {
        id: 2,
        name: "Pizza Paradise",
        cuisine: "Pizza, Italian",
        rating: 4.5,
        deliveryTime: "25-35 mins",
        image: "https://media.swiggy.com/pizza-paradise.jpg",
        isNew: false,
    },
    {
        id: 3,
        name: "Sushi World",
        cuisine: "Japanese, Sushi",
        rating: 4.8,
        deliveryTime: "40-50 mins",
        image: "https://media.swiggy.com/sushi-world.jpg",
        isNew: false,
    },
];


// ── SMALL COMPONENTS ─────────────────────────────────────────

const Logo = () => (
    <div className="logo">
        <h1>🍔 FoodApp</h1>
    </div>
);

const SearchBar = () => (
    <div className="search">
        <input type="text" placeholder="Search for restaurants..." />
        <button>Search</button>
    </div>
);

const NewBadge = () => (
    <span className="new-badge">NEW</span>
);


// ── RESTAURANT CARD ───────────────────────────────────────────

const RestaurantCard = ({ name, cuisine, rating, deliveryTime, image, isNew }) => (
    <div className="res-card">
        <img src={image} alt={name} className="res-image" />
        <div className="res-info">
            {/* Conditional rendering — show badge only if new */}
            {isNew && <NewBadge />}
            <h3 className="res-name">{name}</h3>
            <p className="res-cuisine">{cuisine}</p>
            <div className="res-meta">
                <span>⭐ {rating}</span>
                <span>🕒 {deliveryTime}</span>
            </div>
        </div>
    </div>
);


// ── COMPOSED COMPONENTS ───────────────────────────────────────

const Header = () => (
    <header className="header">
        <Logo />
        <SearchBar />
        <div className="nav-links">
            <a href="#">Sign In</a>
            <a href="#">Cart 🛒</a>
        </div>
    </header>
);

const Body = () => (
    <main className="body">
        <h2 className="section-title">Restaurants near you</h2>
        <div className="res-container">
            {/* Render list using .map() with key prop */}
            {restaurantData.map(restaurant => (
                <RestaurantCard
                    key={restaurant.id}
                    name={restaurant.name}
                    cuisine={restaurant.cuisine}
                    rating={restaurant.rating}
                    deliveryTime={restaurant.deliveryTime}
                    image={restaurant.image}
                    isNew={restaurant.isNew}
                />
            ))}
        </div>
    </main>
);

const Footer = () => (
    <footer className="footer">
        <p>Made with ❤️ by Namaste React</p>
    </footer>
);


// ── ROOT APP COMPONENT ────────────────────────────────────────

const App = () => (
    <>
        <Header />
        <Body />
        <Footer />
    </>
);


// ── RENDER ───────────────────────────────────────────────────

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
WHAT THIS DEMONSTRATES:
========================

✅ JSX instead of React.createElement()
✅ Functional components (arrow functions)
✅ Component composition (App → Header, Body, Footer → smaller components)
✅ React Fragment <></> in App component
✅ Props being passed and destructured
✅ Rendering a list with .map() + key prop
✅ Conditional rendering with &&
✅ JSX expressions with { }
✅ camelCase attributes (className, etc.)

Interview Questions — Quick Fire!

Q: What is JSX?

"JSX stands for JavaScript XML. It's a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript files. JSX isn't valid JavaScript — it's transformed by Babel into React.createElement() calls before the browser runs it. It exists purely for developer convenience — the code is much more readable than nested createElement() calls."

Q: Is JSX valid JavaScript? Can browsers understand it?

"No, JSX is not valid JavaScript and browsers cannot understand it. Babel (or esbuild/swc) must transform JSX into React.createElement() calls first. When you use a bundler like Parcel or Vite, this transformation happens automatically before the code reaches the browser."

Q: What are the differences between JSX and HTML?

"Key differences: JSX uses 'className' instead of 'class' and 'htmlFor' instead of 'for' (because class and for are JavaScript reserved keywords). All event listeners are camelCase (onClick vs onclick). Self-closing tags must have a slash (<img />). Inline styles are objects with camelCase properties (fontSize not font-size). Comments use {/* */} inside JSX. JSX requires one root element."

Q: What is a React Component?

"A React component is a JavaScript function that accepts props as input and returns JSX (a description of what to display). Components are reusable, independent pieces of UI. They must start with a capital letter so React can distinguish them from HTML tags. There are two types: functional components (modern, preferred) and class components (older)."

Q: What are props in React?

"Props (properties) are the mechanism for passing data from a parent component to a child component. They work like function arguments — the parent passes props as attributes on the JSX tag, and the child receives them as a single object. Props are read-only — a component can never modify its own props. This enforces one-way data flow."

Q: Why are props read-only?

"Props are read-only to enforce React's one-way data flow principle. Data always flows from parent to child via props. If a child could modify its props, it would create unpredictable data flow where you couldn't tell where data was coming from. If a child needs to 'update' something, it should call a callback function passed down as a prop, which the parent uses to update its own state."

Q: What is the key prop? Why is it important?

"The key prop is a special prop that helps React identify which items in a rendered list have changed, been added, or removed. React uses keys to match items across re-renders instead of comparing by position. Without keys, React might incorrectly update the wrong components when a list reorders. Keys should be stable, unique IDs — never use array index for mutable lists because it defeats the purpose."

Q: What is Component Composition?

"Component composition is the practice of building complex UIs by combining smaller, simpler components. Instead of one large component doing everything, you break the UI into small reusable pieces — a Logo, a SearchBar, a RestaurantCard — and compose them inside larger components like Header or Body. This keeps each component focused on one responsibility and makes them reusable across the app."

Q: What is React.Fragment and why do we use it?

"React.Fragment (or the shorthand <></>) lets you return multiple elements from a component without adding an extra wrapper DOM node. Without it, you'd need to wrap everything in a div, creating unnecessary 'div soup' that messes up CSS layouts and accessibility. React.Fragment renders its children directly with no wrapper in the DOM."

Q: What are the ways to do conditional rendering in React?

"Four main ways: 1) Ternary operator — for showing A or B (condition ? <A /> : <B />). 2) Short-circuit && — for showing something or nothing (condition && <A />, but beware of 0 rendering). 3) if/else outside the return — for complex conditions before the JSX return. 4) Variable assignment — for multiple conditions where you assign JSX to a variable then render it."

Q: Why can't you use if/else directly inside JSX?

"JSX only allows JavaScript expressions inside { }, not statements. An if/else is a statement, not an expression (it doesn't return a value). That's why we use the ternary operator (which is an expression that evaluates to one of two values) inside JSX. For if/else logic, we write it before the return statement where regular JavaScript is allowed."

Key Points to Remember

Concept Key Takeaway
JSX Syntactic sugar for React.createElement(). Babel transforms it. Browsers never see JSX.
JSX vs HTML className, htmlFor, camelCase events, self-closing tags required, style as object.
Babel JavaScript compiler. Transforms JSX → createElement() and modern JS → browser-compatible JS.
Functional Component A function that takes props and returns JSX. MUST start with Capital letter.
Component Composition Build complex UI by nesting small components. Each has one responsibility.
React.Fragment <></> — return multiple elements without adding a DOM wrapper node. Use React.Fragment for key prop.
Props Arguments to components. Passed as JSX attributes, received as one object. READ-ONLY.
Destructuring props function Card({ name, rating }) — cleaner than props.name, props.rating.
Default Props function Button({ label = "Click Me" }) — defaults in destructuring. Modern preferred way.
.map() + key Use .map() to render lists. Always pass a stable unique key (never index for mutable lists).
Conditional: ternary condition ? A : B — use inside JSX for show A or show B.
Conditional: && condition && A — show A or nothing. BEWARE: 0 && ... renders "0" not nothing!
React DevTools Chrome extension — Components tab to inspect tree, props, state. Profiler tab for performance.

What's Next?

In Chapter 04, we will:

  • Plan a real food delivery app from scratch (like Swiggy/Zomato)
  • Go through Feature Planning → High Level Design → Low Level Design
  • Build Header, Hero, Body, RestaurantCard components for real
  • Work with actual Swiggy API data
  • Learn about props drilling — passing data through multiple levels
  • Understand the children prop — how React handles content between component tags

Make sure you:

  • Practice writing JSX — notice the differences from HTML every time you write it
  • Build the RestaurantCard with real data
  • Open React DevTools and inspect the component tree
  • Try conditional rendering — build a "toggle" that shows/hides content

Keep coding, keep learning! See you in the next one!