Skip to main content

📘 JSX — Complete Theory (Senior-Level React Guide)


1. 🧠 Introduction

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript used in React to describe what the UI should look like. It allows you to write HTML-like code inside JavaScript:
const element = <h1>Hello, world!</h1>;
Behind the scenes, JSX is not HTML — it gets compiled into JavaScript.

Why JSX is Important in React

JSX is central to React because it:
  • Makes UI code declarative and readable
  • Allows combining logic + UI in one place
  • Improves developer experience (DX)
  • Enables powerful tooling (linting, autocomplete)
Without JSX, React code becomes verbose:
React.createElement('h1', null, 'Hello, world!');
With JSX:
<h1>Hello, world!</h1>

When and Why We Use JSX

Use JSX when:
  • Building UI components
  • Rendering dynamic data
  • Structuring layouts
  • Embedding logic inside UI
Why:
  • Easier to understand UI structure
  • Reduces boilerplate
  • Encourages component-based design

2. ⚙️ Concepts / Internal Workings


JSX is Syntax Sugar

JSX gets transpiled (via Babel) into:
React.createElement(type, props, ...children);
Example:
const element = <h1 className="title">Hello</h1>;
Transforms into:
const element = React.createElement(
  'h1',
  { className: 'title' },
  'Hello'
);

JSX Produces React Elements

JSX creates React elements, which are:
  • Plain JavaScript objects
  • Immutable
  • Lightweight representations of UI
Example structure:
{
  type: 'h1',
  props: {
    className: 'title',
    children: 'Hello'
  }
}

Virtual DOM Relationship

JSX → React Elements → Virtual DOM → Real DOM Flow:
  1. JSX defines UI
  2. React converts it to virtual DOM
  3. React compares changes (diffing)
  4. Updates only necessary parts

Expressions Inside JSX

JSX allows embedding JavaScript using {}:
const name = "Rahul";

<h1>Hello {name}</h1>
Important:
  • Only expressions allowed (not statements)
  • You cannot use if, for, etc. directly

JSX Must Return One Parent Element

// ❌ Invalid
return (
  <h1>Hello</h1>
  <p>World</p>
);

// ✅ Valid
return (
  <div>
    <h1>Hello</h1>
    <p>World</p>
  </div>
);
Or use Fragment:
return (
  <>
    <h1>Hello</h1>
    <p>World</p>
  </>
);

JSX Attributes vs HTML Attributes

JSX uses camelCase and JavaScript naming:
HTMLJSX
classclassName
forhtmlFor
onclickonClick

Components in JSX

JSX distinguishes between:
  • Lowercase → HTML elements
  • Uppercase → React components
<MyComponent />   // Component
<div />           // HTML

Self-Closing Tags

JSX requires all tags to be closed:
<img src="image.jpg" />   // ✅
<br />                    // ✅

JavaScript Logic in JSX

You can embed logic like:
const isLoggedIn = true;

return (
  <div>
    {isLoggedIn ? <h1>Welcome</h1> : <h1>Please Login</h1>}
  </div>
);

3. 💻 Syntax & Examples


Basic JSX

const element = <h1>Hello JSX</h1>;

JSX with Variables

const user = "Aman";

const element = <h2>Hello {user}</h2>;

JSX with Functions

function greet(name) {
  return `Hello ${name}`;
}

const element = <h1>{greet("Aman")}</h1>;

JSX with Attributes

const element = <img src="logo.png" alt="Logo" />;

Inline Styling

const style = { color: "red", fontSize: "20px" };

const element = <h1 style={style}>Styled Text</h1>;

Conditional Rendering

const isAdmin = true;

return (
  <div>
    {isAdmin && <p>Admin Panel</p>}
  </div>
);

Rendering Lists

const items = ["Apple", "Banana", "Mango"];

return (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

Nested JSX

const element = (
  <div>
    <h1>Title</h1>
    <p>Description</p>
  </div>
);

Using Components

function Welcome() {
  return <h1>Welcome</h1>;
}

function App() {
  return <Welcome />;
}

4. ⚠️ Edge Cases / Common Mistakes


❌ Using class instead of className

<div class="box"></div> // ❌
<div className="box"></div> // ✅

❌ Returning Multiple Elements Without Wrapper

Fix with:
<>
  <h1>Hello</h1>
  <p>World</p>
</>

❌ Using Statements Instead of Expressions

{if (true) { return <h1>Hello</h1>; }} // ❌
Use ternary:
{true ? <h1>Hello</h1> : null}

❌ Missing key in Lists

items.map(item => <li>{item}</li>) // ❌
Correct:
items.map((item, index) => (
  <li key={index}>{item}</li>
))

❌ Incorrect Inline Styles

<h1 style="color:red"></h1> // ❌
Correct:
<h1 style={{ color: "red" }}></h1>

❌ Boolean Rendering Gotcha

{false}   // renders nothing
{true}    // renders nothing

❌ Using && with Non-Boolean Values

{0 && <h1>Hello</h1>} // renders 0 (unexpected)

❌ Capitalization Errors

<myComponent /> // ❌ treated as HTML
<MyComponent /> // ✅ correct

5. ✅ Best Practices


✔️ Keep JSX Clean and Readable

  • Avoid deeply nested structures
  • Break into smaller components
// Bad
return <div><div><div>Content</div></div></div>;

// Good
return <Content />;

✔️ Use Fragments Instead of Extra divs

<>
  <Header />
  <Main />
</>

✔️ Extract Logic Outside JSX

// ❌ Hard to read
{user.age > 18 ? <Adult /> : <Minor />}

// ✅ Better
const isAdult = user.age > 18;
{isAdult ? <Adult /> : <Minor />}

✔️ Use Meaningful Keys

Avoid index when possible:
<li key={user.id}>{user.name}</li>

✔️ Avoid Inline Functions in Large Lists

// ❌ performance issue
items.map(item => <Item onClick={() => handle(item)} />)

// ✅ better
const handleClick = (item) => { ... };
items.map(item => <Item onClick={handleClick} />)

✔️ Use Consistent Formatting

  • Indent properly
  • Use Prettier / ESLint
  • Keep attributes readable

✔️ Optimize Conditional Rendering

Prefer:
{condition && <Component />}
Over unnecessary ternary:
{condition ? <Component /> : null}

✔️ Avoid Complex Logic in JSX

Move logic outside:
const content = isLoading ? <Loader /> : <Data />;

return <div>{content}</div>;

🧾 Summary

JSX is:
  • A declarative syntax for building UI
  • Compiled into JavaScript (React.createElement)
  • The backbone of React component rendering
Mastering JSX means understanding:
  • How it transforms internally
  • How to write clean, maintainable UI
  • How to avoid subtle bugs and performance issues

🎯 JSX — Senior-Level Conceptual Interview Questions


1. How is JSX fundamentally different from HTML, and why did React choose this design?

Answer:

JSX looks like HTML but is not HTML — it is syntactic sugar for JavaScript function calls (React.createElement). Key Differences:
  • JSX is compiled → HTML is interpreted
  • JSX supports JavaScript expressions → HTML does not
  • JSX produces objects (React elements) → HTML produces DOM nodes
const el = <h1>Hello</h1>;
Compiles to:
React.createElement('h1', null, 'Hello');

Why React chose JSX:

  • Co-locates UI + logic (better component design)
  • Avoids string-based templating (less error-prone)
  • Enables static analysis (linting, type-checking)

Trade-off:

  • Mixing logic and markup can feel messy if not structured well
  • Requires a build step (Babel)

2. What actually happens when JSX is rendered in React?

Answer:

Rendering pipeline:
  1. JSX → compiled into React.createElement
  2. Produces React elements (plain objects)
  3. React builds Virtual DOM
  4. Diffing algorithm compares previous vs new tree
  5. Updates real DOM efficiently
const el = <h1>Hello</h1>;
Becomes:
{
  type: 'h1',
  props: { children: 'Hello' }
}

Why this matters:

  • React avoids direct DOM manipulation
  • Enables high performance via reconciliation

3. Why must JSX return a single parent element?

Answer:

Because JSX compiles into a single JavaScript object, not multiple siblings.
// ❌ invalid
return (
  <h1>Hello</h1>
  <p>World</p>
);

Fix:

return (
  <>
    <h1>Hello</h1>
    <p>World</p>
  </>
);

Reasoning:

  • JavaScript functions can only return one value
  • JSX must represent a single tree root

4. How does React distinguish between HTML elements and components in JSX?

Answer:

React uses naming convention:
  • Lowercase → HTML elements
  • Uppercase → Custom components
<div />        // HTML
<MyComponent /> // React component

Why:

  • JSX compiles into:
    React.createElement(type)
    
  • If type is a string → DOM element
  • If type is a function/class → component

5. Why are JSX expressions restricted to expressions and not statements?

Answer:

JSX embeds JavaScript using {} which expects an expression, not a statement.
{2 + 2}         // ✅ expression
{if (true) {}}  // ❌ statement

Reason:

  • JSX compiles inside function arguments
  • JavaScript only allows expressions in that context

Workaround:

{condition ? <A /> : <B />}
or:
let content;
if (condition) content = <A />;

6. What are React elements, and why are they immutable?

Answer:

React elements are plain JavaScript objects describing UI.
{
  type: 'h1',
  props: { children: 'Hello' }
}

Why immutable?

  • Enables predictable rendering
  • Simplifies diffing algorithm
  • Prevents accidental mutations

Trade-off:

  • Requires re-creation instead of mutation
  • Slight overhead but improves consistency

7. Why does JSX use className instead of class?

Answer:

Because class is a reserved keyword in JavaScript.
<div className="box" />

Reason:

  • JSX is JavaScript, not HTML
  • Must follow JavaScript syntax rules

8. What are the risks of using index as a key in JSX lists?

Answer:

Using index as key can cause incorrect UI updates.
items.map((item, index) => <li key={index}>{item}</li>)

Problem:

  • React uses keys to track identity
  • If order changes → React reuses wrong elements

Example issue:

  • Input fields lose focus
  • State mismatches

Better:

<li key={item.id}>{item.name}</li>

9. Why does {false}, {null}, and {undefined} render nothing in JSX?

Answer:

React treats these values as non-renderable.
{false}  // renders nothing

Why:

  • Simplifies conditional rendering
  • Avoids clutter in DOM

Exception:

{0} // renders "0"

10. What is the difference between && and ternary in JSX rendering?

Answer:

&& (short-circuit)

{isLoggedIn && <Dashboard />}
  • Only renders if true
  • If false → renders nothing

Ternary

{isLoggedIn ? <Dashboard /> : <Login />}
  • Handles both conditions

Pitfall:

{0 && <Component />} // renders 0

11. How does JSX handle event binding compared to traditional DOM?

Answer:

JSX uses synthetic events:
<button onClick={handleClick}>Click</button>

Differences:

  • Uses camelCase
  • Passes function, not string
  • Normalized across browsers

Why:

  • Cross-browser consistency
  • Performance optimizations via event delegation

12. Why are inline styles objects in JSX?

Answer:

<div style={{ color: "red" }} />

Reason:

  • JSX is JavaScript → styles must be objects
  • Allows dynamic styling

Trade-offs:

  • No CSS features like pseudo-selectors
  • Less readable for complex styles

13. What happens if you pass non-primitive values in JSX?

Answer:

Objects/arrays must be handled carefully:
<div>{ {name: "Aman"} }</div> // ❌ error

Why:

  • React cannot render objects directly

Correct:

<div>{JSON.stringify(obj)}</div>

14. How does JSX contribute to performance optimization?

Answer:

Indirectly:
  • Creates lightweight objects
  • Enables Virtual DOM diffing

Important:

JSX itself is not faster — React’s reconciliation is.

Misconception:

JSX ≠ performance boost React architecture = performance boost

15. Why is JSX considered declarative?

Answer:

Because you describe what UI should look like, not how to update it.
<h1>{count}</h1>
Instead of:
element.innerText = count;

Benefit:

  • Easier reasoning
  • Less imperative code
  • Predictable updates

16. What are fragments and why are they important?

Answer:

Fragments allow grouping without extra DOM nodes:
<>
  <h1 />
  <p />
</>

Why important:

  • Avoid unnecessary DOM nesting
  • Cleaner HTML output

17. What is the cost of embedding complex logic inside JSX?

Answer:

Problems:
  • Reduced readability
  • Harder debugging
  • Re-renders become expensive
// ❌ bad
{items.filter(x => x.active).map(...)}

Better:

const activeItems = items.filter(x => x.active);

Principle:

👉 Keep JSX presentation-focused

18. How does JSX impact maintainability in large applications?

Answer:

Positive:
  • Co-locates logic and UI
  • Encourages componentization
Negative:
  • Can become messy if:
    • Overly nested
    • Too much logic inline

Best approach:

  • Break into smaller components
  • Separate concerns logically

🧾 Final Insight

At a senior level, JSX is not just syntax — it is:
  • A design decision that shapes React architecture
  • A bridge between declarative UI and functional programming
  • A tool that must be used carefully to balance readability, performance, and maintainability

🎯 JSX — Senior-Level Multiple Choice Questions (MCQs)


1. What will be rendered?

const value = 0;

return <div>{value && <h1>Hello</h1>}</div>;

Options:

A. <h1>Hello</h1> B. 0 C. Nothing D. Error

✅ Correct Answer: B

Explanation:

  • 0 && <h1> evaluates to 0
  • React renders 0 because it’s a valid renderable value

Why others are wrong:

  • A: Happens only if value is truthy
  • C: Only for false, null, undefined
  • D: No error here

2. What happens here?

const obj = { name: "Aman" };

return <div>{obj}</div>;

Options:

A. Renders [object Object] B. Renders nothing C. Throws error D. Renders JSON

✅ Correct Answer: C

Explanation:

  • React cannot render objects directly → throws error

Why others are wrong:

  • A: Happens in plain JS, not React JSX
  • B: Only for null/undefined
  • D: Requires explicit JSON.stringify

3. What is the output?

return <div>{false}</div>;

Options:

A. false B. Empty div C. Error D. "false"

✅ Correct Answer: B

Explanation:

  • React ignores false, null, undefined

4. Which is TRUE about JSX compilation?

Options:

A. JSX is interpreted by browser B. JSX is converted into HTML strings C. JSX compiles into React.createElement calls D. JSX directly manipulates DOM

✅ Correct Answer: C

Explanation:

  • JSX → JavaScript function calls

Why others are wrong:

  • A: Needs transpilation
  • B: Not string-based
  • D: React handles DOM, not JSX

5. What is the issue here?

function App() {
  return (
    <h1>Hello</h1>
    <p>World</p>
  );
}

Options:

A. Runtime error B. Compile-time error C. Works fine D. Only warning

✅ Correct Answer: B

Explanation:

  • JSX must return one parent → compile-time error

6. What will happen?

const Component = () => <div>Hello</div>;

return <component />;

Options:

A. Renders correctly B. Error C. Treated as HTML element D. Ignored

✅ Correct Answer: C

Explanation:

  • Lowercase → treated as DOM tag

7. What is rendered?

const value = null;

return <div>{value}</div>;

Options:

A. null B. Empty div C. Error D. "null"

✅ Correct Answer: B


8. Which is the correct transformation?

<h1>Hello</h1>

Options:

A. document.createElement() B. React.createElement('h1', null, 'Hello') C. HTML string D. JSX object literal

✅ Correct Answer: B


9. What happens here?

const items = [1, 2, 3];

return items.map(item => <li>{item}</li>);

Options:

A. Works fine B. Warning about keys C. Runtime crash D. Nothing renders

✅ Correct Answer: B

Explanation:

  • Missing key prop → warning

10. What is rendered?

return <div>{[]}</div>;

Options:

A. [] B. Nothing C. Error D. "[]"

✅ Correct Answer: B

Explanation:

  • Empty array renders nothing

11. Which is VALID JSX?

Options:

A. <div class="box"></div> B. <div className="box"></div> C. <div classname="box"></div> D. <div ClassName="box"></div>

✅ Correct Answer: B


12. What will this render?

const num = "5";

return <div>{num + 1}</div>;

Options:

A. 6 B. “6” C. “51” D. Error

✅ Correct Answer: C

Explanation:

  • String + number → string concatenation

13. What is the problem?

return <img src="image.jpg">;

Options:

A. Syntax error B. Missing closing tag C. Runtime error D. Works fine

✅ Correct Answer: A

Explanation:

  • JSX requires self-closing tags

14. What happens?

const Component = () => ({ message: "Hi" });

return <Component />;

Options:

A. Renders object B. Error C. Renders nothing D. Renders JSON

✅ Correct Answer: B

Explanation:

  • Components must return valid JSX, not objects

15. What is rendered?

const value = true;

return <div>{value.toString()}</div>;

Options:

A. true B. “true” C. Nothing D. Error

✅ Correct Answer: B


16. What is the issue?

return <div style="color:red"></div>;

Options:

A. Works fine B. Warning C. Error D. Ignored

✅ Correct Answer: C

Explanation:

  • Style must be object

17. What will happen?

const items = [<li>A</li>, <li>B</li>];

return <ul>{items}</ul>;

Options:

A. Works fine B. Warning about keys C. Error D. Nothing renders

✅ Correct Answer: B


18. What is rendered?

return <div>{NaN}</div>;

Options:

A. NaN B. Nothing C. Error D. “NaN”

✅ Correct Answer: A

Explanation:

  • NaN is rendered as text

🧾 Final Note

These questions test:
  • JSX evaluation rules
  • React rendering nuances
  • Edge-case behavior
  • Internal mechanics

💻 JSX — Senior-Level Coding Problems (18 Real-World Scenarios)


1. Conditional Rendering with Falsy Edge Case

Problem

Render a badge only if notifications > 0.
notifications = 0;

Constraint

  • Must avoid rendering 0

Expected Output

<div></div>

Edge Case

  • notifications = 0 should NOT render 0

Solution

{notifications > 0 && <span>{notifications}</span>}

Explanation

  • Avoid notifications && ... because 0 will render

2. Dynamic Class Assignment Based on State

Problem

Highlight selected item in a list.

Constraint

  • Only one item active at a time

Expected Behavior

Selected item gets class "active"

Solution

<li className={selectedId === item.id ? "active" : ""}>
  {item.name}
</li>

Explanation

  • JSX allows inline expressions for dynamic classes

3. Safe Rendering of Optional Data

Problem

Render user.address.city safely.

Constraint

  • user may be null

Solution

<p>{user?.address?.city || "N/A"}</p>

Edge Case

  • Avoid runtime crash

4. Rendering List with Stable Identity

Problem

Render users with correct keys.

Constraint

  • Items can reorder

Solution

users.map(user => (
  <User key={user.id} user={user} />
))

Explanation

  • Avoid index → prevents UI mismatch

5. Conditional Component Rendering with Fallback

Problem

Render loader or content.

Solution

{isLoading ? <Loader /> : <Content />}

Edge Case

  • Ensure both branches return valid JSX

6. Prevent Rendering Invalid Values

Problem

Avoid rendering objects accidentally.

Solution

<div>{typeof data === "object" ? JSON.stringify(data) : data}</div>

7. JSX Fragment Optimization

Problem

Avoid extra DOM nodes.

Solution

<>
  <Header />
  <Main />
</>

Explanation

  • Cleaner DOM structure

8. Rendering Nested Lists

Problem

Render categories with items.

Solution

categories.map(cat => (
  <div key={cat.id}>
    <h2>{cat.name}</h2>
    {cat.items.map(item => (
      <p key={item.id}>{item.name}</p>
    ))}
  </div>
))

Edge Case

  • Unique keys at each level

9. Inline Function Performance Issue

Problem

Avoid unnecessary re-renders.

Bad

<button onClick={() => handleClick(id)} />

Better

const handle = useCallback(() => handleClick(id), [id]);
<button onClick={handle} />

10. Conditional Attribute Rendering

Problem

Disable button conditionally.

Solution

<button disabled={!isValid}>Submit</button>

11. Rendering Mixed Content Types

Problem

Render string, number, null safely.

Solution

{value ?? "Default"}

12. Handling Boolean Rendering Explicitly

Problem

Show status text.

Solution

<p>{isActive ? "Active" : "Inactive"}</p>

13. Preventing Key Collision in Nested Loops

Problem

Nested lists with potential duplicate IDs.

Solution

items.map((item, i) => (
  <div key={`${item.id}-${i}`}>

14. Dynamic Inline Styles

Problem

Change color dynamically.

Solution

<div style={{ color: isError ? "red" : "green" }}>

15. Rendering Based on Permission Roles

Problem

Only admins see button.

Solution

{user.role === "admin" && <DeleteButton />}

16. Handling Empty Arrays Gracefully

Problem

Show fallback if no data.

Solution

{items.length ? items.map(...) : <p>No data</p>}

17. Avoid Deeply Nested JSX

Problem

Refactor complex UI.

Solution

const content = isLoading ? <Loader /> : <Data />;
return <div>{content}</div>;

18. Rendering Controlled Input Value

Problem

Avoid uncontrolled input warning.

Solution

<input value={value || ""} />

19. Conditional Wrapper Pattern

Problem

Wrap component conditionally.

Solution

const Wrapper = ({ condition, children }) =>
  condition ? <div className="wrapper">{children}</div> : children;

20. Rendering Large Lists Efficiently

Problem

Avoid performance issues.

Solution

const visibleItems = items.slice(0, 50);

Explanation

  • Limit rendered elements

🧾 Final Insight

These problems test:
  • JSX evaluation behavior
  • Real-world rendering patterns
  • Performance considerations
  • Edge-case handling

🧪 JSX — Senior-Level Debugging Challenges (Code Review Style)


1. Rendering 0 Instead of Hiding Element

Buggy Code

{notifications && <Badge count={notifications} />}

❌ What’s Wrong

When notifications = 0, React renders 0 instead of nothing.

🤔 Why It Happens

  • 0 && <Component> evaluates to 0
  • React renders numbers (unlike false, null, undefined)

✅ Fix

{notifications > 0 && <Badge count={notifications} />}

💡 Best Practice

Always explicitly check numeric conditions.

2. Component Not Rendering Due to Lowercase Name

Buggy Code

function header() {
  return <h1>Title</h1>;
}

return <header />;

❌ What’s Wrong

Rendered as HTML <header> instead of custom component.

🤔 Why

Lowercase JSX tags are treated as DOM elements.

✅ Fix

function Header() {
  return <h1>Title</h1>;
}

return <Header />;

💡 Best Practice

Always capitalize component names.

3. Object Rendering Crash

Buggy Code

<div>{user}</div>

❌ What’s Wrong

Throws runtime error.

🤔 Why

React cannot render objects directly.

✅ Fix

<div>{user.name}</div>
or
<div>{JSON.stringify(user)}</div>

💡 Best Practice

Render primitives only.

4. Missing Key in Dynamic List

Buggy Code

items.map(item => <li>{item.name}</li>)

❌ What’s Wrong

React warning + unstable UI behavior.

🤔 Why

Keys help React track element identity.

✅ Fix

items.map(item => <li key={item.id}>{item.name}</li>)

💡 Best Practice

Never omit keys in lists.

5. Using Index as Key Causing UI Bugs

Buggy Code

items.map((item, index) => <Item key={index} item={item} />)

❌ What’s Wrong

UI breaks on reorder.

🤔 Why

Index doesn’t represent stable identity.

✅ Fix

<Item key={item.id} item={item} />

💡 Best Practice

Use stable unique identifiers.

6. Inline Function Causing Re-Renders

Buggy Code

<button onClick={() => handleClick(id)} />

❌ What’s Wrong

New function created every render.

🤔 Why

Causes unnecessary re-renders in children.

✅ Fix

const handle = useCallback(() => handleClick(id), [id]);
<button onClick={handle} />

💡 Best Practice

Avoid inline functions in large lists.

7. Incorrect Conditional Rendering with &&

Buggy Code

{items.length && <List items={items} />}

❌ What’s Wrong

Renders 0 when list is empty.

🤔 Why

0 && ... returns 0

✅ Fix

{items.length > 0 && <List items={items} />}

8. Style Attribute Misuse

Buggy Code

<div style="color: red"></div>

❌ What’s Wrong

Invalid JSX syntax.

🤔 Why

JSX expects style as object.

✅ Fix

<div style={{ color: "red" }}></div>

9. Boolean Value Not Displaying

Buggy Code

<p>{isActive}</p>

❌ What’s Wrong

Nothing renders.

🤔 Why

React ignores boolean values.

✅ Fix

<p>{isActive ? "Active" : "Inactive"}</p>

10. Incorrect Self-Closing Tag

Buggy Code

<img src="image.jpg">

❌ What’s Wrong

JSX syntax error.

🤔 Why

All tags must be closed.

✅ Fix

<img src="image.jpg" />

11. Multiple JSX Elements Without Wrapper

Buggy Code

return (
  <h1>Title</h1>
  <p>Text</p>
);

❌ What’s Wrong

Compilation error.

🤔 Why

JSX must return one root.

✅ Fix

<>
  <h1>Title</h1>
  <p>Text</p>
</>

12. Misusing Ternary with Complex Logic

Buggy Code

{isAdmin ? isLoggedIn ? <Admin /> : <Login /> : null}

❌ What’s Wrong

Hard to read, error-prone.

🤔 Why

Nested ternaries reduce maintainability.

✅ Fix

let content;
if (isAdmin) {
  content = isLoggedIn ? <Admin /> : <Login />;
}

13. Rendering NaN Unexpectedly

Buggy Code

<div>{price * quantity}</div>

❌ What’s Wrong

Displays NaN.

🤔 Why

Invalid arithmetic inputs.

✅ Fix

<div>{isNaN(price * quantity) ? 0 : price * quantity}</div>

14. Conditional Wrapper Bug

Buggy Code

return condition && <Wrapper><Child /></Wrapper>;

❌ What’s Wrong

Returns false when condition fails.

🤔 Why

false is returned instead of JSX.

✅ Fix

return condition ? <Wrapper><Child /></Wrapper> : <Child />;

15. Rendering Undefined Value

Buggy Code

<p>{user.name}</p>

❌ What’s Wrong

Crashes if user is undefined.

🤔 Why

Accessing property of undefined.

✅ Fix

<p>{user?.name || "Guest"}</p>

16. Passing JSX Instead of Component

Buggy Code

const Button = <button>Click</button>;

<Button />

❌ What’s Wrong

Button is JSX, not component.

🤔 Why

JSX is object, not function.

✅ Fix

const Button = () => <button>Click</button>;

17. Improper Spread Props Usage

Buggy Code

<Component {...props} value="fixed" />

❌ What’s Wrong

value may get overridden.

🤔 Why

Order matters in JSX props.

✅ Fix

<Component value="fixed" {...props} />

18. Expensive Computation Inside JSX

Buggy Code

<div>{items.filter(x => x.active).length}</div>

❌ What’s Wrong

Runs every render.

🤔 Why

JSX executes expressions each render.

✅ Fix

const activeCount = useMemo(
  () => items.filter(x => x.active).length,
  [items]
);

🧾 Final Insight

These bugs reflect real production issues involving:
  • JSX evaluation quirks
  • React reconciliation behavior
  • Performance pitfalls
  • Misunderstood rendering rules

🏗️ JSX — Senior-Level Machine Coding Problems (Production-Grade)

These are real-world, interview-level problems focused on JSX usage, component design, and rendering behavior.

1. Smart Notification Center

🧩 Requirements

  • Show list of notifications
  • Show unread count badge
  • Mark as read/unread
  • Auto-hide badge when count = 0

🖥️ UI Behavior

  • Badge disappears when no unread items
  • Clicking item toggles read state

🔄 State Flow

  • notifications[]
  • Derived: unreadCount

⚠️ Edge Cases

  • 0 unread should not render badge
  • Large list updates

🚀 Performance

  • Avoid recalculating unread count unnecessarily

🏗️ Architecture

  • NotificationList
  • NotificationItem
  • Badge

🛠️ Approach

  1. Store notifications
  2. Compute unread count using useMemo
  3. Conditionally render badge:
{unreadCount > 0 && <Badge count={unreadCount} />}

2. Dynamic Form Renderer

🧩 Requirements

  • Render form from JSON schema
  • Support text, select, checkbox
  • Dynamic validation messages

🖥️ UI Behavior

  • Fields appear based on schema
  • Inline validation errors

🔄 State Flow

  • formData
  • errors

⚠️ Edge Cases

  • Missing fields
  • Nested schema

🚀 Performance

  • Avoid re-rendering entire form

🏗️ Architecture

  • FormRenderer
  • FieldRenderer

🛠️ Approach

  • Map schema → JSX components
  • Use controlled inputs

3. Infinite Scroll Feed

🧩 Requirements

  • Load items on scroll
  • Append without resetting DOM

🖥️ UI Behavior

  • Smooth scrolling
  • Loader at bottom

⚠️ Edge Cases

  • Duplicate keys
  • Scroll jump

🚀 Performance

  • Virtualization

🏗️ Architecture

  • Feed
  • FeedItem

🛠️ Approach

  • Maintain list state
  • Render subset using slice/virtualization

4. Role-Based Dashboard Rendering

🧩 Requirements

  • Render components based on user role

🖥️ UI Behavior

  • Admin sees extra controls

⚠️ Edge Cases

  • Undefined role

🏗️ Architecture

  • Dashboard
  • RoleWrapper

🛠️ Approach

{role === "admin" && <AdminPanel />}

5. Searchable Dropdown with Highlighting

🧩 Requirements

  • Filter options
  • Highlight matched text

🖥️ UI Behavior

  • Highlight substring

⚠️ Edge Cases

  • Case sensitivity

🚀 Performance

  • Debounce input

🛠️ Approach

  • Use dangerouslySetInnerHTML carefully OR split text

6. Multi-Step Form Wizard

🧩 Requirements

  • Step navigation
  • Persist state across steps

🖥️ UI Behavior

  • Step-based rendering

🏗️ Architecture

  • Wizard
  • Step

🛠️ Approach

{step === 1 && <Step1 />}

7. Data Table with Sorting & Pagination

🧩 Requirements

  • Sort columns
  • Paginate data

⚠️ Edge Cases

  • Stable keys on reorder

🚀 Performance

  • Memoize sorted data

8. Conditional Wrapper Component

🧩 Requirements

  • Wrap children based on condition

🛠️ Approach

const Wrapper = ({ condition, children }) =>
  condition ? <div>{children}</div> : children;

9. Chat Message Renderer

🧩 Requirements

  • Different UI for sender/receiver

🖥️ UI Behavior

  • Align left/right

🛠️ Approach

<div className={isMe ? "right" : "left"}>

10. Live Character Counter Input

🧩 Requirements

  • Show remaining characters

⚠️ Edge Cases

  • Negative count

🛠️ Approach

<p>{max - value.length}</p>

11. Toggleable Sidebar

🧩 Requirements

  • Collapse/expand sidebar

🛠️ Approach

{isOpen && <Sidebar />}

12. File Upload Preview

🧩 Requirements

  • Show image preview

⚠️ Edge Cases

  • Invalid file types

13. Error Boundary Fallback UI

🧩 Requirements

  • Show fallback on crash

🛠️ Approach

  • Wrap children in boundary

14. Tag Input with Chips

🧩 Requirements

  • Add/remove tags dynamically

🛠️ Approach

tags.map(tag => <Chip key={tag} />)

15. Theme Switcher (Dark/Light)

🧩 Requirements

  • Toggle theme globally

🛠️ Approach

<div className={theme}>

16. Lazy Loaded Component Renderer

🧩 Requirements

  • Load components dynamically

🛠️ Approach

<Suspense fallback={<Loader />}>
  <LazyComponent />
</Suspense>

17. Notification Toast System

🧩 Requirements

  • Show stack of toasts
  • Auto-dismiss

⚠️ Edge Cases

  • Duplicate keys

18. Expandable Accordion List

🧩 Requirements

  • Expand/collapse items

🛠️ Approach

{isOpen && <Content />}

19. Real-Time Search Result List

🧩 Requirements

  • Filter results as user types

🚀 Performance

  • Debounce input

20. Permission-Based Button Rendering

🧩 Requirements

  • Show/hide actions based on permission
{canEdit && <EditButton />}

🧾 Final Insight

These problems evaluate:
  • JSX mastery in real scenarios
  • Component composition
  • Performance thinking
  • Edge-case handling
  • Clean architecture decisions

🎯 JSX — FAANG-Level Interview Questions (Senior Frontend)

These questions simulate real interview depth, focusing on reasoning, trade-offs, and debugging—not memorization.

1. JSX vs Template Engines — Why did React choose JSX?

Follow-up

  • Would you prefer JSX or a template system in large apps? Why?

✅ Strong Answer

JSX enables:
  • Co-location of logic + UI
  • Full power of JavaScript (not limited templating syntax)
  • Static analysis (TypeScript, ESLint)
Trade-off:
  • Mixing concerns can reduce readability if abused

❌ Weak Answer

“JSX is easier to write than HTML” 👉 Fails because it ignores architectural reasoning.

2. Explain what happens internally when JSX is rendered.

Follow-up

  • How does this affect performance?

✅ Strong Answer

  • JSX → compiled to React.createElement
  • Produces React elements (immutable objects)
  • Builds virtual DOM → diff → updates real DOM
Performance comes from reconciliation, not JSX itself.

❌ Weak Answer

“JSX directly renders HTML” 👉 Incorrect mental model.

3. Why is {0 && <Component />} a bug?

Follow-up

  • How would you prevent similar bugs across a codebase?

✅ Strong Answer

  • 0 && expr returns 0
  • React renders numbers → unintended UI
Fix:
{value > 0 && <Component />}
Prevent:
  • ESLint rules
  • Code reviews enforcing explicit conditions

❌ Weak Answer

“It doesn’t work sometimes”

4. When would you avoid using JSX?

Follow-up

  • Have you seen real cases?

✅ Strong Answer

  • Dynamic component factories
  • Performance-critical rendering (manual control)
  • Libraries using React.createElement directly

❌ Weak Answer

“Never” 👉 Shows lack of flexibility.

5. How do keys impact React reconciliation?

Follow-up

  • What happens if keys are unstable?

✅ Strong Answer

  • Keys define identity
  • Incorrect keys → DOM reuse bugs, state mismatch
Example:
key={index} // breaks on reorder

❌ Weak Answer

“Keys remove warnings”

6. How would you debug a component rendering incorrect data after list reorder?

Follow-up

  • What signals point to JSX issues vs state issues?

✅ Strong Answer

  • Check keys first
  • Look for index-based keys
  • Verify component identity mapping

❌ Weak Answer

“Maybe state is wrong”

7. Why are fragments important beyond avoiding extra divs?

Follow-up

  • Any performance implications?

✅ Strong Answer

  • Cleaner DOM → better layout performance
  • Avoid unnecessary wrappers affecting CSS/layout

❌ Weak Answer

“They reduce divs”

8. What are the risks of embedding logic directly inside JSX?

Follow-up

  • Where do you draw the line?

✅ Strong Answer

  • Reduced readability
  • Re-execution on every render
  • Hard debugging
Best practice:
  • Keep JSX declarative
  • Move logic outside

❌ Weak Answer

“It’s fine unless too big”

9. Why can rendering objects in JSX crash the app?

Follow-up

  • How would you safely render unknown data?

✅ Strong Answer

  • React expects renderable primitives
  • Objects are not valid children
Fix:
JSON.stringify(obj)

❌ Weak Answer

“Because React doesn’t like objects”

10. How does JSX influence component design?

Follow-up

  • How would you design for scalability?

✅ Strong Answer

  • Encourages component composition
  • Drives separation of concerns via components

❌ Weak Answer

“It helps writing UI”

11. Explain the performance cost of inline functions in JSX.

Follow-up

  • When is it actually a problem?

✅ Strong Answer

  • New function each render
  • Breaks memoization in children
Problematic in:
  • Large lists
  • Memoized components

❌ Weak Answer

“Inline functions are bad”

12. How would you handle conditional wrappers elegantly?

Follow-up

  • Avoid duplication?

✅ Strong Answer

  • Use wrapper pattern:
const Wrapper = ({ condition, children }) =>
  condition ? <div>{children}</div> : children;

❌ Weak Answer

“Use if statements everywhere”

13. Why is JSX considered declarative?

Follow-up

  • Compare with imperative DOM manipulation

✅ Strong Answer

  • Describes UI state → React handles updates
  • Improves predictability

❌ Weak Answer

“It’s easier”

14. How would you optimize JSX-heavy components?

Follow-up

  • What tools/strategies?

✅ Strong Answer

  • useMemo, React.memo
  • Split components
  • Avoid heavy computation in JSX

❌ Weak Answer

“Use memo everywhere”

15. How do you handle rendering large lists efficiently?

Follow-up

  • What JSX patterns matter?

✅ Strong Answer

  • Virtualization (e.g., windowing)
  • Stable keys
  • Avoid inline logic

❌ Weak Answer

“Use map”

16. What subtle bugs arise from JSX short-circuiting?

Follow-up

  • Other tricky values?

✅ Strong Answer

  • 0, NaN, ""
  • Only false/null/undefined are ignored

❌ Weak Answer

“Sometimes it doesn’t render”

17. How would you enforce JSX consistency across a team?

Follow-up

  • Tools?

✅ Strong Answer

  • ESLint rules
  • Prettier
  • Code reviews
  • Design guidelines

❌ Weak Answer

“Tell developers to follow rules”

18. How do you safely render user-generated content?

Follow-up

  • XSS concerns?

✅ Strong Answer

  • Avoid dangerouslySetInnerHTML
  • Sanitize input
  • Escape content

❌ Weak Answer

“Just render it”

19. What design trade-offs exist in JSX vs separating HTML/JS?

Follow-up

  • When does JSX hurt maintainability?

✅ Strong Answer

Pros:
  • Co-location
  • Flexibility
Cons:
  • Can become messy
  • Harder for designers unfamiliar with JS

❌ Weak Answer

“JSX is always better”

20. How would you debug unnecessary re-renders caused by JSX?

Follow-up

  • What signals do you look for?

✅ Strong Answer

  • Check inline functions
  • Check derived values inside JSX
  • Use React DevTools profiler

❌ Weak Answer

“Use console.log”

🧾 Final Insight

These questions evaluate:
  • Deep understanding of JSX internals
  • Ability to reason about UI behavior
  • Performance awareness
  • Real-world debugging skills
  • Architectural decision-making