Lists, keys and conditional rendering

Real UIs show collections (products, messages, search results) and change based on conditions (logged in or not, loading or loaded, empty or full). Here's how React handles both.

Rendering lists with map

Turn an array of data into an array of elements:

React · live preview
Preview

Keys: why React needs them

Every item in a list needs a key prop: a stable, unique identifier. Remove the key above and watch the Console panel: React warns you.

Keys let React track which item is which when the list changes (items added, removed or reordered), so it updates only what changed and keeps each item's state attached to the right item.

Type a note next to "Apples" in both lists, then click Reverse. With index keys, the note stays in the same position and ends up next to the wrong item!

Key rules: use an ID from your data (database ID, slug). Use the array index only for static lists that never reorder. Never use Math.random().

Filtering and sorting before rendering

Note that we derive visible from state during render, instead of storing a second copy in state. That keeps a single source of truth.

Conditional rendering

There are three common patterns:

⚠️ The 0 && trap: {cart.length && <Cart />} renders a literal 0 when the cart is empty, because 0 is a renderable value. Use cart.length > 0 && instead.

Empty, loading and error states

Professional UIs handle every state, not just the happy path:

Practice: to-do list

Build a to-do list:

  • An input and an "Add" button that adds items (with unique ids, using Date.now() or crypto.randomUUID())
  • Each item has a checkbox to toggle done (strike through done items) and a ✕ button to delete it
  • Show "Nothing to do 🎉" when the list is empty, and "3 of 5 done" underneath
✎ Check your understanding

1.What makes a good key for list items?

2.What does {items.length && <List />} render when items is empty?