React Holiday

Day 15: Key your children

Yesterday, you might have noticed this console warning pop up with our list.

react-unique-key-warning

👶 Give the children keys 🔑

Following the warning above is simple but it leads some questions.

Pass a unique key prop to each component in our map().

<li key={someUniqueKey}>{ability.ability.name}</li>

Why is this needed?

👯‍♀️👯‍♂️ Teamwork!

With arrays, React needs assistance.

To quickly and accurately identify changed, updated, or deleted items, React uses your provided key for diffing.

❄️ How unique is unique? ❄️

Keys need to be unique to that array. ids work great, if you got ‘em.

Unfortunately, our abilities array doesn’t have ids. We can use ability.name because we know each ability is only listed once per character.

<li key={ability.ability.name}>
  {ability.ability.name}
</li>

(Again, id is preferred, when available.)

🙅‍♂️ There’s no i in team 👯‍♂️👯‍♀️

Avoid using the map(item, i) index. It will make updates unpredictable.

Disregard this warning (if you must) but know that this is a common place for tricky bugs to creep in.

Tinker with it

Use the workspace below and explore keys.