Unique keys in tags array in React
In the previous example, we formed our paragraphs in a loop, like this:
const res = arr.map(function(item) {
return <p>{item}</p>;
});
This will work, however, if you look at the console, you will see an error: Warning: Each child in an array or iterator should have a unique "key" prop. In this case, React requires that we give each tag in the loop a unique number, so that it will be easier for React to work with these tags in the future.
This number is added using the attribute key
. In this case, we can take the number of the element in the array as the number. In our case, this number is stored in the variable index
, which means the corrected line will look like this:
const res = arr.map(function(item, index) {
return <p key={index}>{item}</p>;
});
Let's run it - the error from the console will disappear:
function App() {
const arr = [1, 2, 3, 4, 5];
const res = arr.map(function(item, index) {
return <p key={index}>{item}</p>;
});
return <div>
{res}
</div>;
}
Once again: this key
attribute has a service meaning for React, you will understand this point in more depth in the following lessons. For now, just know: if you see such an error - add the key
attribute with a unique value for each tag and the problem will disappear.
The key key
must be unique only within this loop, in another loop the values key
may coincide with the values from another loop.
Modify your solution to the previous problem as described.