Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 6

Rendering Lists with Map and Keys

Recommended resources

Hello! Welcome to your sixth lesson in our "React Fundamentals and JSX" module.

In our last lesson, we mastered conditional rendering, learning how to show or hide UI elements using JavaScript's ternary and logical AND operators. We can now render different UI based on a condition. Today, we'll take that a step further and learn how to render a dynamic list of UI elements from a collection of data, like a list of products, search results, or comments.

This lesson directly addresses the learning outcome: Render lists of elements using the map function and key props. We will leverage your existing JavaScript knowledge of array methods to create dynamic, data-driven interfaces in React.

From Data to UI: Using Array.prototype.map()

In web applications, it's rare to have a hardcoded list of items. Most of the time, you'll fetch an array of data from an API and then display it to the user. React embraces a functional approach to this problem by using JavaScript's built-in Array.prototype.map() method.

As you know from your JavaScript experience, .map() is a powerful tool: it iterates over each item in an array, applies a transformation function to it, and returns a new array containing the transformed items. In React, we use it to transform an array of data (like strings or objects) into an array of JSX elements.

Let's look at the basic pattern.

  1. You start with an array of data.
  2. You use .map() to create a new array of <li> (or other) JSX elements.
  3. You embed this array of elements directly into your JSX using curly braces {}.
// An array of data
const animeTitles: string[] = [
  'Attack on Titan',
  'Jujutsu Kaisen',
  'Vinland Saga'
];

// Use .map() to transform the data into an array of <li> elements
const listItems = animeTitles.map(title => <li>{title}</li>);

// In your component, render the array inside a <ul>
// return <ul>{listItems}</ul>;

You can even do this inline within your component's return statement, which is the most common practice.


Rendering an Array of Objects

While rendering an array of strings is a good start, you'll usually be working with arrays of objects, where each object has multiple properties.

Let's start with a practical demonstration that also incorporates our goal of using TypeScript from the beginning. This video will walk you through the process of mapping over an array of objects and defining the data's "shape" with TypeScript for better code quality and maintainability.

Comprehensive Guide to Rendering an Array in React with TypeScript Types and Interfaces

This video from edutechional provides a great walkthrough of the entire process, from mapping over data to adding TypeScript types. It's a perfect practical demonstration of the core concepts of this lesson.

Please watch these two segments: (00:00 - 04:51): This part covers the core mechanics of using the .map() function to render a list from an array of objects. Pay attention to how properties from the invoice object are accessed within the JSX. (13:44 - 22:40): This segment is particularly relevant for us. It demonstrates how to use TypeScript types and interfaces to define the structure of your data. This makes your components more robust and prevents common bugs, which is a key practice in professional React development.

As you saw in the video, after mapping over the data, you probably noticed a warning in the console:

Warning: Each child in a list should have a unique "key" prop.

This brings us to a critical and mandatory piece of syntax when rendering lists in React.


The key Prop: A Unique Identifier for React

Every time you render a list of elements using .map(), React requires you to add a special prop called key to the outermost element you return inside the callback.

The key must be a string or a number that is unique among its siblings in the list.

interface Anime {
  id: string; // A unique identifier, perfect for a key
  title: string;
  studio: string;
}

const animeList: Anime[] = [
  { id: 'aot_s4', title: 'Attack on Titan', studio: 'MAPPA' },
  { id: 'jjk_s2', title: 'Jujutsu Kaisen', studio: 'MAPPA' },
  { id: 'vs_s1', title: 'Vinland Saga', studio: 'Wit Studio' },
];

function AnimeWatchlist() {
  return (
    <div>
      <h1>My Anime Watchlist</h1>
      <ul>
        {animeList.map(anime => (
          // The key prop is added to the <li> element
          <li key={anime.id}>
            {anime.title} (by {anime.studio})
          </li>
        ))}
      </ul>
    </div>
  );
}
React Component for List Rendering with TypeScript
This TypeScript code shows a functional component `Homepage` that renders a list of users. It uses the `.map()` method to iterate over the `users` state array, creating an `<li>` for each user. Crucially, each `<li>` is given a unique `key` prop (`user.id`) to help React identify and manage the list items efficiently.

So, why is this key prop so important that React enforces it with a warning? It's a "hint" for React's rendering algorithm.

Let's read the official documentation to understand the rules and the high-level reason for this requirement.

Rendering Lists

The official React documentation provides a concise explanation of the purpose of keys and the rules you must follow when using them.

Please read the sections titled 'Keeping list items in order with key', 'Where to get your key', 'Rules of keys', and 'Why does React need keys?'. Focus on the analogy React uses (files on a desktop) and the three rules it presents for keys.

The documentation provides a great analogy: keys are like filenames for your list items. They give each item a stable identity. This identity is crucial for performance when the list changes (items are added, removed, or reordered). We will explore the mechanism behind this—the "reconciliation" algorithm—in more detail in our next lesson.


Choosing the Right key (and Avoiding the Wrong Ones)

The documentation gives clear rules for keys: they must be unique among siblings and they must be stable (not change between re-renders). This leads to a critical best practice:

  • Best: Use a unique and stable ID from your data, such as a database primary key, a UUID, or a slug.
  • Bad: Using the array index as a key. This is a very common anti-pattern.
  • Worst: Generating a key on the fly with Math.random(). This will cause performance issues and bugs with component state.

The warning against using the array index can seem abstract, so let's watch a video that provides a powerful visual demonstration of why it's a bad idea.

React Keys and Lists - Complete Tutorial!

This video from Cosden Solutions visually demonstrates the performance problems caused by not using a key or using an index as a key. Seeing the difference in the browser's DevTools really clarifies the concept.

Watch these key segments to understand the practical impact of keys: (00:18 - 01:19): See what happens when a list is rendered without keys. Notice how the browser re-renders every element when one is deleted. (01:37 - 02:25): Now see the efficient update when a proper key is added. (03:33 - 05:48): This is the most important part. It explains why using the index as a key is just as bad as using no key, showing how the keys shift and confuse React when the list is modified. (06:45 - 08:59): Finally, this section provides practical guidance on what makes a good key.

Test your understanding!

You are building a feature to display a list of user comments. The data for each comment is an object: { commentId: string, authorName: string, text: string }.

The list can be sorted by author name or by the date the comment was posted. Which of the following would be the most appropriate key for the list items?

  1. key={index} (The index from the .map((comment, index) => ...) call)
  2. key={comment.authorName}
  3. key={Math.random()}
  4. key={comment.commentId}
Show answer

The correct answer is 4. key={comment.commentId}.

Here's the breakdown:

  1. index is a bad choice. As the video demonstrated, if the list is re-sorted, the items will get new indices. An item that was at index 2 might move to index 5. React will get confused, leading to inefficient updates and potential bugs with component state.
  2. comment.authorName is a risky choice. While it might seem unique, two different users could have the same name. If two siblings in the list have the same key, React will throw an error. It's also not guaranteed to be stable if users can change their names.
  3. Math.random() is the worst choice. A new random key would be generated on every single render. This tells React that every item is a brand new item, forcing it to destroy the old list and create a new one from scratch, which is terrible for performance.
  4. comment.commentId is the perfect choice. It is designed to be a unique and stable identifier for that piece of data. It will not change, even if the list is re-sorted or filtered. This is exactly what React needs for a key.

Conclusion

You've now learned one of the most fundamental patterns in React: transforming data into UI. By combining JavaScript's .map() function with JSX, you can build dynamic lists for almost any use case.

Key Takeaways:

  • Use the Array.prototype.map() method to transform an array of data into an array of React elements.
  • Always provide a key prop to the top-level element inside the .map() callback.
  • A key must be a string or number that is unique among its siblings.
  • A key must be stable, meaning it shouldn't change across re-renders for the same data item.
  • The best key is a unique ID from your data (e.g., a database ID). Avoid using array indices or randomly generated values.

In our next lesson, we will build upon this foundation and dive deeper into why keys are so important. We'll explore React's reconciliation algorithm to understand how React uses keys to perform efficient updates to the UI, fulfilling the learning outcome: Explain why keys are important for list rendering and reconciliation.