DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Giving Elements a Unique Key Attribute

  • Remember when you create an array of elements, each one needs a key attribute set to a unique value. React uses these keys to keep track of which items are added, changed, or removed. This helps make the re-rendering process more efficient when the list is modified in any way.
  • Code:
const frontEndFrameworks = [
  'React',
  'Angular',
  'Ember',
  'Knockout',
  'Backbone',
  'Vue'
];

function Frameworks() {
  const renderFrameworks = null; // Change this line
  return (
    <div>
      <h1>Popular Front End JavaScript Frameworks</h1>
      <ul>
        {renderFrameworks}
      </ul>
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode
  • Here FreeCodeCamp wants us to map the array Frameworks() to an unordered list, much like in the last challenge. Let's finish writing the map callback to return an li element for each framework in the frontEndFrameworks array.

  • Answer:

function Frameworks() {
  const renderFrameworks = frontEndFrameworks.map(l => <li key = {l}>{l}</li>); 
Enter fullscreen mode Exit fullscreen mode

Note:

  • Keys only need to be unique between sibling elements, they don't need to be globally unique in your application.

Top comments (0)