Rendering Lists in React with .map()

In real-world apps, you often need to display a list of items — like users, products, tasks, etc.

In React, we use JavaScript’s .map() method to render these items dynamically inside JSX.

🎯 Goal: Render a List of Items

Here’s an example list (array):

const fruits = ['🍎 Apple', '🍌 Banana', '🍇 Grape'];

We want to render this like:

🍎 Apple
🍌 Banana
🍇 Grape

Basic Example with .map()

function FruitList() {
  const fruits = ['🍎 Apple', '🍌 Banana', '🍇 Grape'];

  return (
    <div>
      <h2>Fruit List</h2>
      <ul>
        {fruits.map((fruit, index) => (
          <li key={index}>{fruit}</li>
        ))}
      </ul>
    </div>
  );
}

🧠 Explanation

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

⚠️ Why is key important?

React needs a key to:

  • Keep track of each list item
  • Improve rendering performance
  • Avoid bugs during updates

Usually:

  • Use id from your data if available
  • Fall back to index if you don’t have unique IDs

More Realistic Example (Objects)

function UsersList() {
  const users = [
    { id: 1, name: "Alice", age: 21 },
    { id: 2, name: "Bob", age: 18 },
    { id: 3, name: "Charlie", age: 25 },
  ];

  return (
    <div>
      <h2>Users</h2>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.name} - Age {user.age}
          </li>
        ))}
      </ul>
    </div>
  );
}

Leave a Reply

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