← React tutorial

React

Rendering Lists

To render a list, use JavaScript's .map() (from the JavaScript Arrays lesson) to turn an array of data into an array of JSX elements.

Example: a list of students

function StudentList({ students }) {
  return (
    <ul>
      {students.map((s) => (
        <li key={s.id}>{s.name} — {s.track}</li>
      ))}
    </ul>
  );
}

// For students = [{id: 1, name: 'Ada', track: 'Frontend'},
//                  {id: 2, name: 'Chidi', track: 'Cybersecurity'}]
// renders a bulleted list with both students' names and tracks.

Why the key prop matters, not just React being picky

Each item needs a unique key prop — here, s.id — so React can track exactly which rendered item corresponds to which piece of data across re-renders, especially when items get added, removed, or reordered. Using the array's index as a key (key={i}) instead of a real id looks fine at first, but breaks in a specific way once the list order can change: React starts matching the wrong data to the wrong rendered element, since the index stayed the same even though what's actually at that position changed. Prefer a real, stable id whenever one exists — the array index only as a genuine last resort, when the list itself never reorders or changes.

Example
function StudentList({ students }) {
  return (
    <ul>
      {students.map((s) => (
        <li key={s.id}>{s.name}</li>
      ))}
    </ul>
  );
}
Output
For students = [{id: 1, name: 'Ada'}, {id: 2, name: 'Chidi'}], renders a bulleted list with items "Ada" and "Chidi".