🟢 Basics – React + Next.js Foundation · Lesson 08
Lists, Keys & Conditional Rendering
Render a list with map()
React has no for loop inside JSX. Instead you turn an array of data into an array of elements with JavaScript's .map().
JSX
const subjects = ['Maths', 'Science', 'English', 'Computer']
export default function Page() {
return (
<ul>
{subjects.map((s) => (
<li key={s}>{s}</li>
))}
</ul>
)
}• Maths
• Science
• English
• Computer
Why keys matter
A key is a unique label for each list item. When the list changes, React compares keys to know which item was added, removed or moved, and updates only that item.
Good keys ✅
- Database id:
key={c.id} - Slug:
key={post.slug} - Unique text that never repeats
Risky keys ⚠️
- Array index when the list can change
Math.random()— changes every render- Same value for two items
Lists of objects
JSX – components/CourseList.jsx
const courses = [
{ id: 1, title: 'C Programming', fee: 2499, level: 'Beginner' },
{ id: 2, title: 'Next.js', fee: 4499, level: 'Intermediate' },
{ id: 3, title: 'Python + AI', fee: 3499, level: 'Beginner' },
]
export default function CourseList() {
return (
<div className="grid">
{courses.map((c) => (
<article key={c.id} className="card">
<h3>{c.title}</h3>
<p>₹{c.fee.toLocaleString('en-IN')} · {c.level}</p>
</article>
))}
</div>
)
}Filter and sort before rendering
Prepare the data with normal array methods, then map it. Keep the JSX simple.
JSX
const beginner = courses
.filter((c) => c.level === 'Beginner') // keep only beginner courses
.sort((a, b) => a.fee - b.fee) // cheapest first
const total = courses.reduce((sum, c) => sum + c.fee, 0)
<p>{beginner.length} beginner courses · Total fees ₹{total}</p>
{beginner.map((c) => <p key={c.id}>{c.title}</p>)}2 beginner courses · Total fees ₹10497
C Programming
Python + AI
💡
.sort() changes the original array. When sorting state or props, copy first: [...courses].sort(...).Conditional rendering: 4 ways
JSX
function Status({ isLoggedIn, cartCount, role, user }) {
// 1. Early return
if (!user) return <p>Loading…</p>
return (
<div>
{/* 2. Ternary: one or the other */}
{isLoggedIn ? <button>Logout</button> : <button>Login</button>}
{/* 3. && : show only when true */}
{cartCount > 0 && <span className="badge">{cartCount} in cart</span>}
{/* 4. Variable chosen before JSX */}
{role === 'admin' ? <a href="/admin">Admin panel</a> : null}
</div>
)
}| Pattern | When to use |
|---|---|
if (...) return ... | Whole component changes (loading, not logged in) |
a ? <X/> : <Y/> | Show one of two things |
cond && <X/> | Show or show nothing |
null | Render nothing explicitly |
Always handle empty states
JSX
{posts.length === 0 ? (
<p className="empty">No articles yet. Check back soon! ✍️</p>
) : (
posts.map((p) => <PostCard key={p.slug} post={p} />)
)}The EduSite courses page shows "No course found" when a search has no results — a small detail that makes a site feel professional.
Example: marks table with grades
JSX – components/MarksTable.jsx
const students = [
{ roll: 1, name: 'Riya', marks: 91 },
{ roll: 2, name: 'Aman', marks: 58 },
{ roll: 3, name: 'Sara', marks: 32 },
]
const grade = (m) => (m >= 90 ? 'A+' : m >= 60 ? 'A' : m >= 33 ? 'B' : 'Fail')
export default function MarksTable() {
return (
<table>
<thead><tr><th>Roll</th><th>Name</th><th>Marks</th><th>Grade</th></tr></thead>
<tbody>
{students.map((s) => (
<tr key={s.roll} style={{ color: s.marks < 33 ? 'crimson' : 'inherit' }}>
<td>{s.roll}</td><td>{s.name}</td><td>{s.marks}</td><td>{grade(s.marks)}</td>
</tr>
))}
</tbody>
</table>
)
}Roll Name Marks Grade
1 Riya 91 A+
2 Aman 58 B
3 Sara 32 Fail (shown in red)
Common mistakes
- Forgetting
key→ console warning and buggy updates. - Putting the key on an inner element instead of the outermost one returned by
map. {list.length && ...}shows 0 when empty → uselist.length > 0 &&.- Using curly braces with an arrow function and forgetting
return:map(c => { <li/> })renders nothing. Use parentheses or addreturn.
Summary
- Use
.map()to render arrays; give each item a stable uniquekey. - Filter, sort and calculate before the JSX.
- Show/hide UI with early return, ternary,
&&ornull. - Always design an empty state.
✅ Practice
Make a to-do list with an input and "Add" button. Show "Nothing to do 🎉" when empty, and a ✕ button on each item that removes it (use filter).
Frequently Asked Questions
What should I use as a key?
A value that is unique and stable for each item, such as a database id or a slug. Avoid the array index when items can be added, removed or reordered.
Why does React warn "Each child in a list should have a unique key prop"?
You returned elements from .map() without a key. Add key={item.id} (or another unique value) to the outermost element returned in the map.
Why does {count && …
} show 0 on the screen?
When count is 0, the expression evaluates to 0 and React renders the number. Write {count > 0 &&
…
} instead.Can I use if-else inside JSX?
Not directly. Use the ternary operator inside JSX, or put an if statement before the return and store the JSX in a variable.
