← 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".
Ready to go further?

These free tutorials are a preview, our Frontend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Frontend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account