Files
freeCodeCamp/guide/english/react/keys/index.md
KurtWayn3 95e541882c Add Keys with Examples (#32942)
* Add Keys with Examples

* fix: added front matter block
2019-02-10 19:32:24 -08:00

1.0 KiB

title
title
Keys

Keys

Keys are the eyes and ears on your application battlefield letting React know which items have changed or were added.

const bestCereal = ['cookie crisp','waffle crisp','fruit loops','cinnamon toast crunch','cocoa puffs'];
const cerealItems = bestCereal.map((cereal) =>
  <ul key={cereal}>
    {cereal}
   </ul>
);

Notice that the keys selected were all unique. The key is required to be unique. If you are unable to provide a unique key from the list of items you are iterating over, you can use the index.

const troops = ['general','major','platoon leader','cadet','cadet'];
const troopItems = troops.map((soldier, index) =>
  <ul key={index}>
    {soldier}
   </ul>
);

Although it is not recommended to use index if the order of items change. Many in the React community use index as a last resort.

More Information