The keys in React JS

The ‘React Way’ to render a List
  • Use Array.Map
  • Not a For Loop
  • Give Each Item in Unique Key.
  • Avoid using Array Index As the Key

A key is a special string attribute that needs to be included when using lists of elements.

Example

const ids = [1,2,3,4,5];
const listElements = ids.map((id)=>{
 return(
 <li key={id.toString()}>
   {id}
 </li>
 )
})

Importance of keys
Keys help react identify which elements were added, changed or removed.
Keys should be given to array elements for providing a unique identity for each element.
Without keys, React does not understand the order or uniqueness of each element.
With keys, React has an idea of which particular element was deleted,edited, and added.
Keys are generally used for displaying a list of data coming from an API.

Leave a comment

Your email address will not be published. Required fields are marked *