intro-to-programming

πŸ“‹ Rendering Lists & Using Keys

In React, rendering a list of items is a very common task β€” and doing it right helps performance and avoids rendering bugs. The secret ingredient? .map() and the key prop.


πŸ”’ Why Lists Matter

Lists appear everywhere:

Rendering them dynamically keeps your UI flexible and data-driven.


🧠 Core Concepts

βœ… .map() to Render Lists

React doesn’t have a built-in loop like for.
Instead, use .map() to transform an array into JSX elements.

const fruits = ['🍎 Apple', '🍌 Banana', '🍊 Orange'];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit) => (
        <li>{fruit}</li>
      ))}
    </ul>
  );
}

πŸ”Έ Problem: React will warn you that each child needs a unique key prop.


πŸ”‘ What is the key Prop?

The key is a special prop React uses to identify which items in a list have changed, been added, or removed.

<ul>
  {fruits.map((fruit, index) => (
    <li key={index}>{fruit}</li>
  ))}
</ul>

πŸ“¦ Example: Rendering a List of Users

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

function UserList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

βœ… Each item has a unique key β†’ no warning βœ… React can re-render efficiently when data changes


⚠️ Common Mistakes


πŸ“š Best Practices

Do This Avoid This
Use .map() to render lists Using for loops in JSX
Provide a unique key prop Omitting the key
Use stable IDs if possible Using Math.random() as key
Keep list rendering pure Mutating arrays during render

πŸ§ͺ Bonus: Conditional rendering

{
  items.length === 0 ? (
    <p>No items found.</p>
  ) : (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

πŸ“˜ Learn More


πŸš€ Summary

Concept Description
.map() Used to loop through arrays and render JSX
key Helps React identify items in a list
Good Keys Unique, stable values like IDs
Avoid Index Don’t use index as key in dynamic lists