JSX Rules, Expressions & Conditional Rendering
Quick Answer: JSX lets you write HTML-like UI right inside JavaScript. Follow three core rules: return one root element, use {} for JavaScript expressions, and always give list items a unique key prop.
Imagine Meena runs a hospital appointment portal in Chennai. At 9:00 AM, Arjun opens the app to check available cardiology slots.
Arjun's screen must show three different things based on live data: a loading spinner, a "No slots left" message, or a list of open doctor slots.
How do we write clean JSX that handles dynamic data, switches UI states safely, and renders lists without bugs?
1. Why Do JSX Rules Matter?
The problem without clean JSX
JSX looks like HTML, so beginners often paste plain HTML directly into a React component. That causes instant build errors and broken lists.
Example 1: Broken JSX in Meena's hospital component
This component breaks three core JSX rules at once.
function SlotHeader() {
return (
<h2 class="title">Chennai Clinic</h2>
<p>Patient: Arjun</p>
<img src="logo.png">
);
}
What happens when Vite compiles this
SyntaxError: Adjacent JSX elements must be wrapped in an enclosing tag. Warning: Invalid DOM property `class`. Did you mean `className`?
This fails before the app even opens in the browser.
- Returning two sibling tags (
<h2>and<p>) without a parent breaks JavaScript's single return value. - Using
classinstead ofclassNameclashes with JavaScript's reservedclasskeyword. - Leaving
<img>unclosed causes a strict JSX syntax error.
The solution: Structured JSX with Expressions
JSX = JavaScript XML, a syntax that lets you describe UI elements inside JavaScript functions.
Fragment (<>...</>) = an invisible wrapper that groups multiple elements without adding extra <div> tags to the DOM.
Conditional Rendering = showing different UI branches based on JavaScript expressions like ? : or &&.
Live Switchboard: How JSX Evaluates Arjun's Appointment Screen
Watch how changing component state picks one JSX branch and updates the browser screen.
if (isLoading) return <Spinner />;if (slots.length === 0) return <Empty />;slots.map(s => <SlotCard key={s.id} />)React evaluates your JavaScript conditions top-to-bottom and renders only the matching JSX branch. Every item from .map() carries a stable key.
2. JSX Rules, Expressions, and Lists in Practice
Curly Braces ({}) = a window inside JSX where you can run any JavaScript expression that produces a value (variables, math, ternary checks, or .map()).
Key Prop = a unique string or number attached to each list item so React knows which item changed, moved, or was deleted.
Example 2: Clean JSX with expressions, conditionals, and keyed lists
This component powers Arjun's appointment screen in Meena's portal.
export default function AppointmentList({ patientName, isLoading, slots }) {
if (isLoading) {
return <p className="status">Checking doctor slots...</p>;
}
return (
<>
<h2 className="title">Welcome, {patientName}</h2>
{slots.length === 0 ? (
<p>No cardiology slots available today.</p>
) : (
<ul>
{slots.map((slot) => (
<li key={slot.id}>
{slot.doctor} – {slot.time}
{slot.isUrgent && <strong> (Priority)</strong>}
</li>
))}
</ul>
)}
</>
);
}
Expected rendered HTML output
Welcome, Arjun - Dr. Meena - 10:30 AM (Priority) - Dr. Karthik - 11:15 AM
Notice how <>...</> wraps the heading and list cleanly. The ternary operator (? :) handles the empty state, and key={slot.id} gives each row a stable identity.
3. Messy JSX vs. Clean JSX
| Broken / Messy JSX | Clean React JSX |
|---|---|
| Multiple sibling tags without a wrapper. | Wrapped in one parent or Fragment <>...</>. |
class="card" and onclick="...". |
className="card" and onClick={...}. |
slots.map((s, i) => <li key={i}>). |
slots.map((s) => <li key={s.id}>). |
Writing if/else statements inside {}. |
Using early returns, ? :, or &&. |
The important terms to remember
- JSX = HTML-like syntax compiled into JavaScript function calls by Vite/Babel.
- Expression = code that returns a value (allowed inside
{}); statements likeiforforare not allowed inside{}. - Key Prop = a unique ID on list items that helps React update only changed rows.
Design tip: Never write {slots.length && <ul>...</ul>}. When slots.length is 0, React actually prints the number 0 on the screen! Always write {slots.length > 0 && <ul>...</ul>}.
4. Common Mistakes to Avoid
1. Using the array index as a key
If Arjun books the first slot and it gets removed from the list, every remaining item shifts its index. React mixes up their state and highlights the wrong doctor.
Better approach: Always use a stable database ID like key={slot.id}.
2. Putting if-else statements directly inside curly braces
Writing {if (isLoading) return ...} inside JSX causes a syntax error because if is a statement, not an expression.
Better approach: Use an early return above the JSX, or use a ternary operator (condition ? A : B).
5. Interview Questions & Practice
Question 1: Why does React need a key prop when rendering lists?
What the interviewer expects: Understanding of React's reconciliation (diffing) process and why stable IDs prevent UI bugs.
Strong answer: "React uses the key prop to track which list items were added, changed, or removed between renders. In a hospital slot list, using a unique slot.id lets React remove just one booked slot without re-rendering every other doctor card or mixing up local state."
What interviewers expect at different levels
- Junior developer: Knows basic JSX rules (
className, single root, self-closing tags) and how to render a list with.map(). - Senior developer: Explains the
0 && <Component />pitfall, why index keys break controlled inputs, and keeps JSX readable with early returns. - Technical architect: Designs clean component boundaries so complex conditional rendering does not turn into deeply nested ternaries.
Practice Tasks
Beginner: Railway ticket status badge
Write a small component that takes isConfirmed and shows a green "Confirmed" badge if true, or a yellow "Waitlist" badge if false.
Expected result: A single component using a ternary operator inside <span className={...}>.
Intermediate: UPI transaction history
Render a list of UPI payments (id, receiver, amount) using .map(). Show "No recent payments" when the array is empty.
Hint: Check payments.length === 0 before mapping, and use key={tx.id}.
Advanced: Food delivery live order tracker
Build an OrderStatus component that handles four states: loading, error, empty, and activeOrders.
- Use early returns for
loadinganderror. - Show a "Priority Delivery" tag using
&&only whenorder.isExpressis true.
Challenge: Avoid nested ternaries completely so a teammate can read the file in 10 seconds.
6. Next Steps
- Open your Vite React project and create
src/AppointmentList.jsxusing Example 2. - Test all three states by passing
isLoading={true}, an empty array[], and a 2-item array to see the UI switch cleanly.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.