Skip to main content
React Introduction
CHAPTER 10 Beginner

Rendering Lists and Keys

Updated: May 13, 2026
20 min read

# Rendering Lists and Keys

1. Introduction

Web applications are essentially lists of data. A Twitter feed is a list of tweets. An Amazon search result is a list of products. A Gmail inbox is a list of emails. As a React developer, you will constantly need to take an array of data and convert it into an array of UI components. In this chapter, we will learn how to use the JavaScript map() function to render lists efficiently in React.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the Array.map() function to generate JSX elements.
  • Render dynamic lists from data arrays.
  • Understand the critical importance of the key prop in React lists.
  • Avoid common pitfalls when generating list elements.

3. Beginner-Friendly Explanations

The map() Function

React relies heavily on standard JavaScript array methods. The most important one is .map(). map() takes an array, runs a function on every single item in that array, and returns a new array with the transformed items.

In React, we use map() to take an array of *data* (like strings or objects) and transform it into an array of *JSX elements*.

4. Syntax Explanation

Rendering a Simple Array of Strings

Let's say we have an array of programming languages.

```jsx id="ch10_ex1" // Example React component function TechStack() { const languages = ['React', 'JavaScript', 'CSS', 'HTML'];

return ( <ul> {languages.map((lang, index) => { // We return a JSX element for every string in the array return <li key={index}>{lang}</li>; })} </ul> ); }

123456789
### The Concept of "Keys"
Notice the `key={index}` in the code above? **This is mandatory in React.**
When React renders a list of items, it needs a way to keep track of each individual item. If an item is added, removed, or reordered in the array, React needs to know *exactly which one* changed so it can update the Virtual DOM efficiently, rather than re-rendering the entire list.

A `key` is a unique string or number that uniquely identifies an item among its siblings.

### Rendering an Array of Objects (Real-World Data)
In real apps, data comes from a database as an array of objects. When iterating over database objects, you should ALWAYS use the database `id` as the key, not the array index.

jsx id="ch10_ex2" // Example React component function TaskList() { const tasks = [ { id: 't1', title: 'Buy groceries', isDone: false }, { id: 't2', title: 'Walk the dog', isDone: true }, { id: 't3', title: 'Learn React', isDone: false }, ];

return ( <div> <h2>My Tasks</h2> {tasks.map((task) => ( // Using the unique database ID as the key! <div key={task.id} className="task-item"> <input type="checkbox" checked={task.isDone} readOnly /> <span>{task.title}</span> </div> ))} </div> ); }

1234567891011121314151617181920212223
## 5. Output Explanations
In `TaskList`, the `.map()` method loops 3 times. It generates three `<div>` elements. React looks at the `key` props (`t1`, `t2`, `t3`). If task `t2` is deleted later, React knows exactly which `<div>` to remove from the screen without touching `t1` or `t3`.

## 6. Real-World Examples
Any time you see repeating UI patterns, `map()` is being used behind the scenes:
- Spotify playlist: Mapping over an array of song objects to render `<TrackRow />` components.
- Netflix homepage: Mapping over an array of movies to render `<MovieThumbnail />` components.

## 7. Common Mistakes
- **Forgetting the `key` prop:** Your app will still work, but React will yell at you with a red warning in the browser console: *"Warning: Each child in a list should have a unique 'key' prop."*
- **Using the array `index` as a key for dynamic lists:** If you use `key={index}` and the array order changes (e.g., you sort the list or delete the first item), React gets horribly confused and can render the wrong data or mess up input focus. Only use `index` if the list is completely static and will never change order or length.
- **Putting the key on the wrong element:** The key must go on the *outermost* element returned from the map function.

## 8. Best Practices
- Always extract complex list items into their own components. For example, instead of mapping and returning 20 lines of HTML, do this: `{users.map(u => <UserCard key={u.id} data={u} />)}`.

## 9. Exercises
1. Create an array of 5 of your favorite movies (just strings).
2. Use `.map()` to render them as an ordered list (`<ol>`). Use the array index as the key.

## 10. Mini Project: Todo List Renderer
Let's build a polished UI that renders a list of user comments from a mock database.

jsx id="ch10_proj1" // Example React component import React from 'react';

// Mock data array const comments = [ { id: 101, author: "Alice", avatar: "https://i.pravatar.cc/150?img=1", text: "This article was so helpful, thank you!" }, { id: 102, author: "Bob", avatar: "https://i.pravatar.cc/150?img=11", text: "I'm still struggling with the concept of keys." }, { id: 103, author: "Charlie", avatar: "https://i.pravatar.cc/150?img=3", text: "Great explanation on the map function." } ];

export default function CommentSection() { return ( <div className="max-w-2xl mx-auto p-6 bg-gray-50 min-h-screen"> <h2 className="text-2xl font-bold mb-6 text-gray-800">Discussion ({comments.length})</h2> <div className="space-y-4"> {/* Mapping through the data */} {comments.map((comment) => ( // KEY IS ON THE OUTERMOST WRAPPER <div key={comment.id} className="bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex gap-4"> <img src={comment.avatar} alt={comment.author} className="w-12 h-12 rounded-full" /> <div> <h4 className="font-bold text-gray-900">{comment.author}</h4> <p className="text-gray-600 mt-1">{comment.text}</p> </div> </div> ))} </div> </div> ); } ``

11. Coding Challenges

Challenge 1: Start with an array of numbers
[1, 2, 3, 4, 5]. Map over them to create 5 buttons. The text of the button should be the number. Use the number itself as the key.

12. MCQs with Answers

Q1: Which JavaScript array method is primarily used in React to render lists? A)
.forEach() B) .reduce() C) .map() D) .filter() *Answer: C (Because map returns a new array, while forEach returns undefined).*

Q2: Why is using the array index as a key dangerous in dynamic lists? A) It causes syntax errors. B) Indexes change if items are added or removed, causing React to render incorrectly or lose state. C) Indexes take up too much memory. D) It is actually the recommended best practice. *Answer: B*

13. Interview Questions

  • Q: Why do lists in React require a key prop?
  • Q: Can I use Math.random() to generate a key? *(Answer: NO! This forces React to recreate the element from scratch on every single render, destroying performance and internal state).*

14. FAQs

Can I filter a list before rendering it? Yes! You can chain JavaScript methods.
{users.filter(u => u.isActive).map(u => <UserCard key={u.id} />)}

15. Summary

To render lists of data in React, use the JavaScript
.map() method to transform an array of data into an array of JSX elements. Never forget the key prop on the outermost returned element, and ideally, always use a unique, stable identifier from your data (like a database ID) rather than the array index.

16. Next Chapter Recommendation

You can now map over data to create forms, but how do you actually capture what a user types into a form? In Chapter 11: React Forms and User Input, we will bridge the gap between HTML
<input>` elements and React State using Controlled Components.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·