State and Event HandlingLesson 2.5
How to render lists and use keys correctly in React
Array.map for rendering, key prop purpose, key uniqueness requirements, index as key pitfalls, conditional rendering, short-circuit evaluation
Rendering Lists in React
React renders lists by mapping arrays to JSX. The key prop is required on every list item — it tells React which items changed, were added, or removed during re-renders.
Basic List Rendering
function TaskList({ tasks }) {
return (
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.title}
</li>
))}
</ul>
);
}
// Usage
const tasks = [
{ id: 1, title: 'Buy groceries' },
{ id: 2, title: 'Write tests' },
{ id: 3, title: 'Code review' },
];Why Keys Matter
Keys must be unique among siblings and stable across renders. Using array index as a key breaks when items are reordered or deleted — React will incorrectly reuse DOM nodes.
// Bad — index shifts when items are added/removed
tasks.map((task, index) => <li key={index}>{task.title}</li>)
// Good — stable unique ID
tasks.map(task => <li key={task.id}>{task.title}</li>)Conditional Rendering
function Status({ isLoading, data }) {
return (
<div>
{isLoading && <p>Loading...</p>}
{!isLoading && data && <p>{data}</p>}
{!isLoading && !data && <p>No data found.</p>}
</div>
);
}Use && for show/hide. Use ternary for either/or. Avoid returning 0 with && — use Boolean(count) && or a ternary to prevent rendering the number 0.
