Uniqueness of Keys
We have told many times while discussing keys that keys assigned to the array elements must be unique. By this, we did not mean that the keys should be globally unique. All the elements in a particular array should have unique keys. That is, two different arrays can have the same set of keys.
Example 3: In the below code, we have created two different arrays menuItems1 and menuItems2. You can see in the below code that the keys for the first 5 items for both arrays are the same still the code runs successfully without any warning.
Javascript
import React from "react" ; import ReactDOM from "react-dom" ; // Component to be extracted function MenuItems(props) { const item = props.item; return <li>{item}</li>; } // Component that will return an // unordered list function Navmenu(props) { const list = props.menuitems; const updatedList = list.map((listItems) => { return <MenuItems key={listItems.toString()} item={listItems} />; }); return <ul>{updatedList}</ul>; } const menuItems1 = [1, 2, 3, 4, 5]; const menuItems2 = [1, 2, 3, 4, 5, 6]; ReactDOM.render( <div> <Navmenu menuitems={menuItems1} /> <Navmenu menuitems={menuItems2} /> </div>, document.getElementById( "root" ) ); |
Output: This will be the output of the above code
ReactJS Keys
React JS keys are a way of providing a unique identity to each item while creating the React JS Lists so that React can identify the element to be processed.
Table of Content
- What is a key in React ?
- Assigning keys to the list
- Issue with index as keys
- Difference between keys and props in React
- Using Keys with Components
- Incorrect usage of keys
- Correct usage of keys
- Uniqueness of Keys
Contact Us