Give Sibling Elements a Unique Key Attribute - an inquiry

I managed to cobble together an answer, after much googling and some sneak-peeking at solution :blush:

But I have a question. If key is meant to assign a unique ID to each item in the list, how is{item + 1} enough? What if, by mistake or design, 2 items in the list are the same? Then there would be 2 items with the same key…no?

Thank you.

Your code so far


const frontEndFrameworks = [
  'React',
  'Angular',
  'Ember',
  'Knockout',
  'Backbone',
  'Vue',
];

function Frameworks() {
  const renderFrameworks = frontEndFrameworks.map((item) =>
  <li key={item+1}>{item}</li>
); 
  return (
    <div>
      <h1>Popular Front End JavaScript Frameworks</h1>
      <ul>
        {renderFrameworks}
      </ul>
    </div>
  );
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/give-sibling-elements-a-unique-key-attribute

1 Like

Actually, you can try changing the code to understand what’s going on, for ex:

frontEndFrameworks.forEach((item) => {
  console.log(item+1);
})

the output will be

React1
Angular1
Ember1
Knockout1
Backbone1
Vue1

so as long as the names are not the same the keys will not as well. But, I don’t think this is the best solution because what if the items are all the same?

frontEndFrameworks.forEach((item,idx) => {
  console.log(idx);
})

output

0
1
2
3
4
5

I think this is better, basically idx here (second param) is the index of the loop item, you can name it i, idx or something like that.

1 Like