Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Lists and Keys

Lists and Keys in Reactjs

When working with dynamic data in React.js, you often need to render lists of elements, such as items in a todo list, posts in a feed, or options in a dropdown menu. To efficiently render and update lists, React provides a concept called "lists" and a special attribute called "keys." Here's how lists and keys work in React:

1. Rendering Lists:

  • To render a list of elements, you can use the map function to transform an array of data into an array of React elements.
  • For example, to render a list of names, you can do the following in JSX:
const names = ["Alice", "Bob", "Charlie"];

const nameList = names.map((name, index) => 
  • {name}
  • ); return
      {nameList}
    ;      

     

     

    2. The key Attribute:

    • In the example above, the key attribute is added to each <li> element. The key is a special attribute that helps React identify which items have changed, been added, or been removed. It must be unique among sibling elements.
    • Keys are not meant to be accessed by your component. They are for React's internal use to optimize updates.

    3. Why Keys are Important:

    • Keys help React efficiently update and re-render elements in a list. When an item in the list changes, React can identify which specific item needs to be updated instead of re-rendering the entire list. This improves performance.
    • Keys also assist React in identifying items that have been added or removed from the list.

    4. Using Unique Identifiers:

    • For lists of dynamic data fetched from an API or database, it's recommended to use unique identifiers as keys. Common choices include database IDs or UUIDs.
    • Avoid using array indices as keys if the list can change. Using indices can lead to incorrect rendering when items are added or removed.

    5. Lists in Class Components:

    • When rendering lists in class components, you can assign keys as a property to the elements. Here's an example:
    class NameList extends React.Component {
      render() {
        const names = ["Alice", "Bob", "Charlie"];
        const nameList = names.map((name, index) => 
  • {name}
  • ); return
      {nameList}
    ; } }      

     

     

    6. Lists in Functional Components:

    • In functional components, you can create an array of elements and directly return it within JSX. Here's the functional component version of the previous example:
    function NameList() {
      const names = ["Alice", "Bob", "Charlie"];
      return (
        
      {names.map((name, index) => (
    • {name}
    • ))}
    ); }      

     

     

    In summary, when rendering lists in React, always assign a unique key attribute to each element. Keys help React efficiently update and manage the rendering of lists, making your application more performant and responsive when dealing with dynamic data.