Lesson 2 — Rendering, lists, and conditional UI¶
Objective¶
Render filterable topic cards with stable identity and explicit empty states.
Prerequisites¶
Lesson 1 — App anatomy and JSX. You should be comfortable mapping arrays and using controlled inputs.
Mental Model¶
React reconciles element trees. A key identifies an item among siblings; it is not passed as a prop and must represent domain identity rather than position.
Concept¶
When a list re-renders, React uses key to decide which existing component instances to keep, move, or recreate. A key tied to domain identity preserves local state across reordering and filtering. Conditional rendering should be explicit and provide a usable branch for every state.
Example¶
type Topic = { id: string; title: string };
function TopicList({ topics }: { topics: Topic[] }) {
const filtered = topics.filter((t) => t.title.toLowerCase().includes('react'));
if (filtered.length === 0) {
return <p role="status">No matching topics.</p>;
}
return (
<ul>
{filtered.map((topic) => (
<li key={topic.id}>{topic.title}</li>
))}
</ul>
);
}
Real-World Usage¶
Searchable tables, product catalogs, notification feeds, and task boards all need stable identity and meaningful empty states.
Common Mistakes¶
- Using array indexes as keys when reordering is possible.
- Leaving
undefinedorfalseas the only empty branch, which renders nothing silently. - Treating
keyas a prop that can be read by the child component.
Mini Lab¶
Task¶
Map typed topics into cards. Add a controlled search input and derive matching topics. Render a useful empty state. Compare stable IDs with array indexes while reordering data.
Constraints¶
- Test search by role and visible text.
- Reorder items and confirm local item state remains attached to the correct topic.
Expected Result¶
Searching filters the list, empty queries show a helpful message, and reordering preserves the checked or expanded state of each topic.
Hints¶
Derive filtered data during render. Use topic.id as the key and a real heading/link hierarchy inside each card.
Knowledge Check¶
- Why can index keys corrupt state?
- When does React preserve or reset component state?
- Is
items.length && <List />always safe?
Challenge¶
A designer asks you to drag-and-drop the list. What keying strategy would you choose, and what would you expect to happen to local state during the drag?
Summary¶
Keys are identity, not props. Derive filtered data during render and provide an explicit, accessible empty state.