NelsonLabs
React Fundamentals/Rendering Lists

Rendering Lists

Rendering lists is fundamental to almost every React app — a feed of posts, a list of products, a navigation menu, a course list. React has specific requirements about how you render them.

Rendering arrays with .map()
jsx
const courses = [
  { id: 1, title: "HTML Fundamentals", chapters: 10 },
  { id: 2, title: "CSS Styling", chapters: 12 },
  { id: 3, title: "JavaScript Basics", chapters: 14 },
];

function CourseList() {
  return (
    <ul>
      {courses.map(course => (
        <li key={course.id}>
          <strong>{course.title}</strong> — {course.chapters} chapters
        </li>
      ))}
    </ul>
  );
}

The key prop

The key prop is required when rendering arrays. React uses keys to track which item is which — so when the list changes (an item is added, removed, or reordered), React knows exactly which DOM nodes to update rather than re-rendering the whole list.

Keys — rules and best practices
jsx
// Good: use a unique, stable ID from your data
{users.map(user => <UserCard key={user.id} user={user} />)}

// Acceptable: use the value if it's guaranteed unique
{tags.map(tag => <Tag key={tag} label={tag} />)}

// Bad: using the array index as key
// This causes bugs when items are added, removed, or reordered
{courses.map((course, index) => (
  <CourseCard key={index} course={course} />  // avoid this
))}

// The key must be unique among siblings (not globally unique)
// React will warn you in the console if you forget it