Correct usage of keys
Example 2: The below example shows the correct usage of keys.
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 menuItems = [1, 2, 3, 4, 5]; ReactDOM.render( <Navmenu menuitems={menuItems} />, document.getElementById( "root" ) ); |
Output: In the below-given output you can clearly see that this time the output is rendered but without any type of warning in the console, it is the correct way to use React Keys.
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