React Lesson 9: Lists and Keys

⚛️ React CourseLesson 9 of 15 · 60% complete

Rendering lists of data is fundamental in React. Every time you show a list of items — products, users, messages — you use this pattern.

Rendering Arrays with .map()

function FruitList() {
  const fruits = ["Apple", "Banana", "Cherry", "Date"];
  
  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

Why Keys Matter

// Keys help React identify which items changed
// Keys must be UNIQUE within the list
// Use stable IDs, not array indexes (if possible)

// ❌ Avoid using index as key (causes bugs with reordering)
list.map((item, index) => <li key={index}>{item}</li>);

// ✅ Use a unique ID if available
users.map(user => <li key={user.id}>{user.name}</li>);

// ✅ If no ID, generate one or use the value if unique
tags.map(tag => <span key={tag}>{tag}</span>);

Rendering Objects

const products = [
  { id: 1, name: "Laptop", price: 999, stock: 5 },
  { id: 2, name: "Mouse", price: 29, stock: 50 },
  { id: 3, name: "Keyboard", price: 79, stock: 20 }
];

function ProductList() {
  return (
    <div className="products">
      {products.map(product => (
        <div key={product.id} className="product-card">
          <h3>{product.name}</h3>
          <p>${product.price}</p>
          <span>{product.stock} in stock</span>
        </div>
      ))}
    </div>
  );
}

🏋️ Practice Task

Create a TodoList component with useState. Start with 3 todos. Show all todos in a list. Add a Delete button next to each todo that removes it. Add an input + Add button to add new todos.

💡 Hint: For delete: const removeTodo = (id) => setTodos(todos.filter(t => t.id !== id)). For add: spread old todos and add new one.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *