One common way to do this is by using the index of the current item in the iteration, in combination with a prefix or suffix that is unique to the component.
For example, consider the following code:
const items = [{id: 1, text: "Item 1"}, {id: 2, text: "Item 2"}, {id: 3, text: "Item 3"}];
return (
<ul>
{items.map((item, index) => (
<li key={`item-${index}`}>{item.text}</li>
))}
</ul>
);
In this example, each li element is given a key based on the index of the item in the items array, combined with the string “item-”. This ensures that each key is unique, even if the items in the items array change.
It’s important to note that using the index as the key is not the recommended way to generate keys, because if the order of items changes, the keys will no longer match the correct items, which can lead to unexpected behavior. It’s better to use a unique identifier for each item, such as an ID, if one is available.
UIID library
One popular library for generating unique keys is the uuid library, which generates universally unique IDs. Here’s an example of how you can use it in a React component:
import { v4 as uuidv4 } from 'uuid';
const items = [{id: 1, text: "Item 1"}, {id: 2, text: "Item 2"}, {id: 3, text: "Item 3"}];
return (
<ul>
{items.map(item => (
<li key={uuidv4()}>{item.text}</li>
))}
</ul>
);
In this example, each li element is given a unique key generated by the uuidv4()
function from the uuid library.
Custom generator
You can also write your own custom key generator, for example, by combining a prefix or suffix with the current timestamp:
const items = [{id: 1, text: "Item 1"}, {id: 2, text: "Item 2"}, {id: 3, text: "Item 3"}];
const generateKey = prefix => `${prefix}-${new Date().getTime()}`;
return (
<ul>
{items.map(item => (
<li key={generateKey("item")}>{item.text}</li>
))}
</ul>
);
In this example, each li
element is given a unique key generated by the generateKey()
function, which combines the string “item” with the current timestamp.