βš›οΈπŸŒ² React Holiday


We'll start from basics and get all the way to Suspense, Hooks, and advanced composition!
Each day is a 2-3 minute read with CodeSandbox and quick assignments.
Check out 2017 (below) for examples.

Day 15: Key your children

December 15, 2017

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.


chantastic

Written by chantastic.
Follow his nonsense on Twitter.