🔥 0
0
Lesson 8 of 10 20 min +100 XP

Rendering Lists

Most apps display lists of data. React makes this easy with JavaScript's map().

Basic List Rendering

const items = ['Apple', 'Banana', 'Cherry'];

function FruitList() {
  return (
    <ul>
      {items.map(item => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

Why Keys Matter

Keys help React identify which items changed, were added, or removed.

// ✅ Good: Unique, stable ID
{users.map(user => <UserCard key={user.id} user={user} />)}

// ❌ Bad: Using index (can cause bugs when list changes)
{users.map((user, index) => <UserCard key={index} user={user} />)}

Key Rules

  • Unique among siblings - Don't need to be globally unique
  • Stable - Don't generate keys randomly
  • No index - Avoid using array index when items can reorder

Common List Patterns

// Filter and map
{todos
  .filter(todo => !todo.completed)
  .map(todo => <TodoItem key={todo.id} {...todo} />)}

// Transform data
{products.map(product => (
  <ProductCard
    key={product.id}
    name={product.name}
    price={`${product.price.toFixed(2)}`}
  />
))}

Try building lists below!

Conditional Rendering