React

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 *