Bird
Raised Fist0
Reactframework~5 mins

Rendering lists in React

Choose your learning style10 modes available
Introduction

Rendering lists in React helps show many items on the screen easily. It lets you display things like menus, messages, or products by repeating a small piece of code for each item.

Showing a list of tasks in a to-do app.
Displaying a menu with many options.
Listing messages in a chat app.
Showing products in an online store.
Rendering search results from a query.
Syntax
React
function Component() {
  const items = [/* array of data */];
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Always add a unique key prop to each list item to help React track changes.

Use map() to transform each item into a React element.

Examples
Rendering a simple list of strings using their index as key.
React
function FruitList() {
  const fruits = ['Apple', 'Banana', 'Cherry'];
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}
Handling an empty list by showing a message.
React
function EmptyList() {
  const items = [];
  return (
    <ul>
      {items.length === 0 ? <li>No items found</li> : items.map(item => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}
Rendering a list with only one item.
React
function SingleItemList() {
  const items = [{ id: 1, name: 'Only item' }];
  return (
    <ul>
      {items.map(item => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}
Rendering a list of objects using a unique string id as key.
React
function ListWithObjects() {
  const users = [
    { id: 'u1', name: 'Alice' },
    { id: 'u2', name: 'Bob' },
    { id: 'u3', name: 'Charlie' }
  ];
  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}
Sample Program

This React component shows a list of tasks. It uses useState to hold tasks. Each task is shown as a list item with a unique key. This helps React update the list efficiently.

React
import React, { useState } from 'react';

function TaskList() {
  const [tasks, setTasks] = useState([
    { id: 101, title: 'Buy groceries' },
    { id: 102, title: 'Walk the dog' },
    { id: 103, title: 'Read a book' }
  ]);

  return (
    <main>
      <h1>My Tasks</h1>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>{task.title}</li>
        ))}
      </ul>
    </main>
  );
}

export default TaskList;
OutputSuccess
Important Notes

Using a unique key helps React know which items changed, added, or removed. Avoid using indexes as keys if the list can change order.

Rendering large lists can slow down your app. Consider techniques like windowing for very long lists.

Remember to handle empty lists gracefully to improve user experience.

Summary

Use map() to render lists in React.

Always add a unique key prop to each list item.

Handle empty or single-item lists carefully for good UI.

Practice

(1/5)
1. What is the main purpose of using the map() method when rendering lists in React?
easy
A. To filter out unwanted items from the list
B. To sort the list items alphabetically
C. To transform an array of data into an array of React elements
D. To add styles to each list item

Solution

  1. Step 1: Understand the role of map() in React

    The map() method is used to take an array of data and create a new array by transforming each item. In React, this means turning data into React elements.
  2. Step 2: Identify what map() does in rendering lists

    When rendering lists, map() creates a React element for each item, which React can then display on the screen.
  3. Final Answer:

    To transform an array of data into an array of React elements -> Option C
  4. Quick Check:

    map() creates elements from data [OK]
Hint: Remember: map() turns data into elements [OK]
Common Mistakes:
  • Thinking map() sorts or filters data
  • Using map() without returning elements
  • Confusing map() with forEach()
2. Which of the following is the correct way to add a unique key to list items in React?
easy
A. {items.map(item => <li key={item.id}>{item.name}</li>)}
B. {items.map(item => <li key={Math.random()}>{item.name}</li>)}
C. {items.map(item => <li key="index">{item.name}</li>)}
D. {items.map(item => <li>{item.name}</li>)}

Solution

  1. Step 1: Understand the importance of keys in React lists

    Keys help React identify which items changed, added, or removed. They must be unique and stable for each list item.
  2. Step 2: Evaluate each option for key usage

    {items.map(item => <li>{item.name}</li>)} has no key, so React will warn. {items.map(item => <li key={item.id}>{item.name}</li>)} uses a unique id from the item, which is correct. {items.map(item => <li key="index">{item.name}</li>)} uses a string 'index' for all keys, which is not unique. {items.map(item => <li key={Math.random()}>{item.name}</li>)} uses Math.random(), which changes every render and is unstable.
  3. Final Answer:

    {items.map(item => <li key={item.id}>{item.name}</li>)} -> Option A
  4. Quick Check:

    Unique stable keys = {items.map(item => <li key={item.id}>{item.name}</li>)} [OK]
Hint: Use unique stable keys from data, not random or fixed strings [OK]
Common Mistakes:
  • Omitting the key prop entirely
  • Using index or random values as keys
  • Using non-unique keys causing rendering bugs
3. What will be the output of this React code snippet?
const fruits = ['Apple', 'Banana', 'Cherry'];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit, index) => <li key={index}>{fruit}</li>)}
    </ul>
  );
}
medium
A. SyntaxError due to missing keys
B.
  • Apple
  • Banana
  • Cherry
C.
  • 0
  • 1
  • 2
D. Empty list rendered

Solution

  1. Step 1: Understand the map function output

    The map() creates a list item for each fruit with the fruit name as content.
  2. Step 2: Check the key usage and rendering

    Using index as key is allowed (though not ideal), so React renders the list with fruit names inside <li> tags.
  3. Final Answer:

    <ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul> -> Option B
  4. Quick Check:

    map() renders fruit names as list items [OK]
Hint: map() returns elements with content, keys don't affect output text [OK]
Common Mistakes:
  • Confusing keys with displayed content
  • Expecting errors from using index keys
  • Thinking map returns indexes instead of values
4. Identify the error in this React list rendering code:
const numbers = [1, 2, 3];

function NumberList() {
  return (
    <ul>
      {numbers.map(number => <li>number</li>)}
    </ul>
  );
}
medium
A. Missing key prop on list items
B. numbers array is empty, so no output
C. Syntax error due to arrow function
D. The word 'number' is rendered literally, not the variable

Solution

  1. Step 1: Analyze the JSX inside map

    The code writes <li>number</li> which renders the literal text 'number', not the variable value.
  2. Step 2: Identify how to fix variable rendering

    To render the variable, it should be inside curly braces: <li>{number}</li>.
  3. Final Answer:

    The word 'number' is rendered literally, not the variable -> Option D
  4. Quick Check:

    JSX needs curly braces for variables [OK]
Hint: Use curly braces {} to render variables in JSX [OK]
Common Mistakes:
  • Forgetting curly braces around variables
  • Ignoring missing key warnings
  • Assuming array is empty without checking
5. You have a list of user objects with possible duplicate IDs:
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Carol' }
];

function UserList() {
  return (
    <ul>
      {users.map((user, index) => <li key={`${user.id}-${index}`}>{user.name}</li>)}
    </ul>
  );
}

What problem can occur and how to fix it?
hard
A. Duplicate keys cause rendering issues; use unique keys like index or combined values
B. No problem; React handles duplicate keys automatically
C. Syntax error due to duplicate IDs in objects
D. List will render only first two users ignoring duplicates

Solution

  1. Step 1: Understand React's key requirement

    Keys must be unique to help React track items. Duplicate keys cause rendering bugs or warnings.
  2. Step 2: Identify the duplicate key issue in code

    Two users share id=1, so keys are not unique. This can confuse React during updates.
  3. Step 3: Suggest a fix for unique keys

    Use a unique key like combining id and index: key={`${user.id}-${index}`} or a unique identifier.
  4. Final Answer:

    Duplicate keys cause rendering issues; use unique keys like index or combined values -> Option A
  5. Quick Check:

    Unique keys prevent rendering bugs [OK]
Hint: Keys must be unique; combine id with index if duplicates exist [OK]
Common Mistakes:
  • Ignoring duplicate keys causing UI bugs
  • Assuming React auto-fixes duplicate keys
  • Using only index keys without data context
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard