VDone Demo VDone Demo
Home
  • Articles

    • JavaScript
  • Study Notes

    • JavaScript Tutorial
    • Professional JavaScript
    • ES6 Tutorial
    • Vue
    • React
    • TypeScript: Build Axios from Scratch
    • Git
    • TypeScript
    • JS Design Patterns
  • HTML
  • CSS
  • Technical Docs
  • GitHub Tips
  • Node.js
  • Blog Setup
  • Learning
  • Interviews
  • Miscellaneous
  • Practical Tips
  • Friends
About
Bookmarks
  • Categories
  • Tags
  • Archives
GitHub (opens new window)

Nikolay Tuzov

Backend Developer
Home
  • Articles

    • JavaScript
  • Study Notes

    • JavaScript Tutorial
    • Professional JavaScript
    • ES6 Tutorial
    • Vue
    • React
    • TypeScript: Build Axios from Scratch
    • Git
    • TypeScript
    • JS Design Patterns
  • HTML
  • CSS
  • Technical Docs
  • GitHub Tips
  • Node.js
  • Blog Setup
  • Learning
  • Interviews
  • Miscellaneous
  • Practical Tips
  • Friends
About
Bookmarks
  • Categories
  • Tags
  • Archives
GitHub (opens new window)
  • 核心概念

    • Introduction to JSX
    • Rendering Elements
    • Components & Props
    • State & Lifecycle
    • Handling Events
    • Conditional Rendering
    • Lists & Keys
      • Rendering Multiple Components
      • Basic List Component
      • Keys
      • Extracting Components with Keys (Set keys inside map)
      • Keys Must Only Be Unique Among Siblings
        • Cannot Use key as a Prop Name for Child Components
      • Embedding map() in JSX
    • Forms
    • Lifting State Up (Shared State)
    • Composition vs Inheritance
    • Thinking in React
  • 高级指引

  • Hook

  • 案例演示

  • 《React》笔记
  • 核心概念
xugaoyi
2021-03-24
Contents

Lists & Keys

# 07. Lists & Keys

Given the code below, we use the map() (opens new window) function to double every item in an array of numbers, and we log the new array doubled:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
1
2
3

In React, transforming arrays into lists of elements (opens new window) is nearly identical.

# Rendering Multiple Components

const numbers = [1,2,3]
// Use map to place values into li elements, forming an array of li tags, then insert them into ul
const listItems = numbers.map(number => {
  <li>{numbers}</li>
})

ReactDOM.render(
	<ul>{listItems}</ul>
  document.getElementById('root')
)
1
2
3
4
5
6
7
8
9
10

# Basic List Component

Combining the list into a component:

function NumberList(props){
  const numbers = props.numbers
  const listItems = numbers.map(number => {
    // Remember to add a key to list elements
    <li key={number.toString()}>
    	{number}
    </li>
  })

  return (
  	<ul>{listItems}</ul>
  )
}

const numbers = [1,2,3]
ReactDOM.render(
	<NumberList numbers={numbers} />,
  document.getElementById('root')
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# Keys

Keys help React identify which items have changed, are added, or are removed. Therefore, you should give each element in an array a stable identity.

A key should be a unique string that an element has in the list. Typically, we use IDs from our data as keys:

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
       {todo.text}
  </li>
);
1
2
3
4
5

When items don't have stable IDs, you may use the item index as a key as a last resort:

const todoItems = todos.map((item, index) =>
  // Only use index as key when items have no stable IDs
  <li key={index}>
        {item.text}
  </li>
);
1
2
3
4
5
6

We don't recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

If you choose not to assign an explicit key, React will default to using indexes as keys.

# Extracting Components with Keys (Set keys inside map)

Keys only make sense in the context of the surrounding array.

Example: Incorrect key usage

function ListItem(props) {
  const value = props.value;
  return (
    // Wrong! There is no need to specify the key here:
    <li key={value.toString()}>
      {value}
    </li>
  );
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // Wrong! The key should have been specified here:
    <ListItem value={number} />
  );

  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

A good rule of thumb is: elements inside the map() call need keys.

#

# Keys Must Only Be Unique Among Siblings

Keys used within arrays should be unique among their siblings. However, they don't need to be globally unique. We can use the same keys when we produce two different arrays.

function Blog(props) {
  const sidebar = (    <ul>
      {props.posts.map((post) =>
        <li key={post.id}>          {post.title}
        </li>
      )}
    </ul>
  );
  const content = props.posts.map((post) =>    <div key={post.id}>      <h3>{post.title}</h3>
      <p>{post.content}</p>
    </div>
  );
  return (
    <div>
      {sidebar}      <hr />
      {content}    </div>
  );
}

const posts = [
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
  <Blog posts={posts} />,
  document.getElementById('root')
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# Cannot Use key as a Prop Name for Child Components

Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);
1
2
3
4
5
6

In the example above, the Post component can read props.id, but cannot read props.key.

# Embedding map() in JSX

JSX allows embedding any expression (opens new window) in curly braces, so we could inline the map() result:

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {
        numbers.map((number) =>
            <ListItem key={number.toString()} value={number} />
        )
      }
    </ul>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12

Sometimes this results in clearer code, but this style can also be abused.

Like in JavaScript, it is up to you to decide whether it is worth extracting a variable for readability. Keep in mind that if the map() body is too nested, it might be a good time to extract a component (opens new window).

Edit (opens new window)
#React
Last Updated: 2026/03/21, 12:14:36
Conditional Rendering
Forms

← Conditional Rendering Forms→

Recent Updates
01
How I Discovered Disposable Email — A True Story
06-12
02
Animations in Grid Layout
09-15
03
Renaming a Git Branch
08-11
More Articles >
Theme by VDone | Copyright © 2026-2026 Nikolay Tuzov | MIT License | Telegram
  • Auto
  • Light Mode
  • Dark Mode
  • Reading Mode