ReactJS | Keys | List
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated or deleted. In other words we can say that keys are used to give an indentity to the elements in the lists. The next thing that comes in mind is that what should be good to be choose as key for the items in lists. It is recommended to use a string as a key that uniquely identifies the items in the list
incorrect usage
Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const menuItems = [1, 2, 3, 4, 5];
ReactDOM.render(<App menuItems={menuItems} />, document.getElementById("root"));
app.js
import React from "react";
import "./style.css";
export default function App(props) {
console.log(props);
const list = props.menuItems;
const updatedList = list.map(listItems => {
return <MenuItems item={listItems} key={listItems.toString()} />;
});
return <ul>{updatedList}</ul>;
}
function MenuItems(props) {
const item = props.item;
const lbl = <li>{item}</li>;
// key={listItems.toString()} Warning not removed
// This is because we had not assigned key to the elements we are returning to the map() iterator.
return lbl;
}
correct usage of keys :
This is because we had not assigned key to the elements we are returning to the map() iterator.
Reference
reactjs-keys
React File Upload
ReactJS | Importing and Exporting
ReactJS | Lifecycle of Components
ReactJS | Implementing State & Lifecycle