React πŸŽ„

πŸŽ‰ Now on video! πŸ“Ί
Buy, buy, buy!!!

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.

← Previous
Next β†’

Learn other React stuff...