Start learning free

LESSON 126 OF 161 · FRONTEND: FRONTEND WITH AI

The AI Used the Index as Key in JavaScript

Practice

An AI assistant wrote the shop's cart in src/Cart.jsx. Each cart line is a CartLine with its own state: the quantity the visitor typed. To draw the lines, the AI wrote:

{lines.map((line, index) => (
  <CartLine
    key={index}
    line={line}
    onRemove={onRemove}
  />
))}

React uses the key to match each line with the state it had on the last draw. key={index} means "the first line", "the second line", not "the Mug". It works until a visitor removes a line near the top: every line below moves up one place and takes the state of the line that was there before.

A key that names the item keeps its state with it. For example, a list of notes, each with its own checkbox state: notes.map((note) => <Note key={note.id} note={note} />).

The check adds the Mug, the Teapot and the Lamp, types 3 for the Mug and 2 for the Lamp, then removes the Mug. With index keys, the Mug's 3 jumps onto the Teapot, and the Teapot's 1 onto the Lamp:

> click "Remove Mug"
  screen changes:
      main
        section "Cart"
          list
    -       item: Mug $12
    -         field "Quantity of Mug": "3" (number)
    -         button: Remove Mug
            item: Teapot $22
    -         field "Quantity of Teapot": "1" (number)
    +         field "Quantity of Teapot": "3" (number)
            item: Lamp $29
    -         field "Quantity of Lamp": "2" (number)
    +         field "Quantity of Lamp": "1" (number)

Your cart must take away only the Mug:

> click "Remove Mug"
  screen changes:
      main
        section "Cart"
          list
    -       item: Mug $12
    -         field "Quantity of Mug": "3" (number)
    -         button: Remove Mug

Your task: in src/Cart.jsx, give CartLine a quantity state that starts at 1, and a number field named "Quantity of " + line.name that shows and sets it. Then key each CartLine by line.id, not by its index.


Assignment
Follow the Coding Tutorial to add each cart line's quantity and its field, then key the cart's lines by product id.


Hint
The key goes on the CartLine inside map, just above line={line}. A product's id is the same on every draw; an index is only a place in the list.


STEP 1 OF 3
    Ctrl + Enter to check

    Aiui Index Keys in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free