Start learning free

LESSON 116 OF 161 · FRONTEND: ACCESSIBLE, FAST, CORRECT

Keys Are Identity

Practice

A component can keep its own state, like the note a visitor types into one line of the cart. When the list draws again, React has to know which new line is which old one, so it can give each line its state back.

Without a key, React matches lines by position: first to first, second to second. Remove the first line and every line below moves up one place, so it gets the state of the line that used to sit there. A note ends up on the wrong product.

A key is a name tag that stays with the item. Give each item something that belongs to it, like its id:

{reviews.map((review) => (
  <Review key={review.id} review={review} />
))}

The index from map is no better than no key at all: it is the position again. The check types a note for Mug and one for Lamp, then removes Mug. Your cart must print:

> type "gift wrap" into "Note for Mug"
    +   field "Note for Mug": "gift wrap"
> type "for Dad" into "Note for Lamp"
    +   field "Note for Lamp": "for Dad"
> click "Remove Mug"
    -   item: Mug $12
    -     field "Note for Mug": "gift wrap"
    -     button: Remove Mug

Teapot's and Lamp's notes don't change: "for Dad" stays on Lamp.

Your task: in src/Cart.jsx, give each CartLine a note state and a field named "Note for " + line.name, write removeLine and pass it as onRemove, then key each line by its product id.


Assignment
Follow the Coding Tutorial to add a note to each cart line, make Remove work, and key the lines so each note leaves with its own product.


Hint
The key goes on the component that map returns, CartLine, not inside it. Use something that belongs to the product, not its place in the list.


STEP 1 OF 6
    Ctrl + Enter to check