SyntaxStudy
Sign Up
React Rendering Lists with .map() and the key Prop
React Beginner 2 min read

Rendering Lists with .map() and the key Prop

Rendering a list of items in React is done with the JavaScript `Array.prototype.map()` method inside JSX. Each call to `map()` transforms a data array into an array of JSX elements, which React renders in order. This is more powerful than a template loop because it is pure JavaScript: you can chain `filter()`, `slice()`, `sort()`, and other array methods before calling `map()`, and you can extract the mapping logic into its own function or component. Every element in a rendered list must have a unique `key` prop. The key helps React identify which items changed, were added, or were removed during reconciliation. Without keys, React would have to re-render the entire list on every change; with keys, it can update only the affected items. Keys must be unique among siblings but do not need to be globally unique. They must also be stable — do not use array indices as keys when the list can be reordered or items can be inserted/removed, because index-based keys cause incorrect updates and animation glitches. The best key is a stable, unique identifier from your data — a database row ID, a UUID, or a slug. When no such identifier exists (for example, a list of static strings), array indices are acceptable as a last resort, but you should be aware of the limitations. React will print a console warning if you forget to add keys, making this one of the most visible beginner mistakes.
Example
// ── Basic list rendering ──────────────────────────────────────
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

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

// ── List of objects with IDs ──────────────────────────────────
const users = [
  { id: 1, name: 'Alice',   role: 'admin'  },
  { id: 2, name: 'Bob',     role: 'editor' },
  { id: 3, name: 'Charlie', role: 'viewer' },
];

function UserTable() {
  return (
    <table>
      <thead>
        <tr><th>Name</th><th>Role</th></tr>
      </thead>
      <tbody>
        {users.map(user => (
          <tr key={user.id}>        {/* key on the outermost element */}
            <td>{user.name}</td>
            <td>{user.role}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ── Filter + map ──────────────────────────────────────────────
function AdminList() {
  const admins = users.filter(u => u.role === 'admin');

  if (admins.length === 0) return <p>No admins found.</p>;

  return (
    <ul>
      {admins.map(u => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

export default UserTable;