React.js Lists and Keys

Rendering Lists in React.js

To render lists in React.js, you can use the map() function to iterate over an array of data and generate a list of React elements.

Example:

                                      
                                      class List extends React.Component {
  render() {
    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
      
  • {number}
  • ); return ( <ul> {listItems} </ul> ); } }

    In functional components, you can do the same:

    Example:

                                          
                                          function List() {
      const numbers = [1, 2, 3, 4, 5];
      const listItems = numbers.map((number) =>
        <li>{number}</li>
      );
    
      return (
        <ul>
          {listItems}
        </ul>
      );
    }
    
                                          
                                        

    Using Keys for Efficient List Rendering

    Instead of using regular lists you can use the React components to render them and make every child in the list to have unique "key" prop.

    Keys in React are identifying which items have been changed, added or removed by telling where it needs to update the elements in the DOM.

    It does that React turns out to be a fast tool to make the list of DOM updated with only a few passed statements of time.

    Example:

    In below example, we use the key prop with a unique value for each list item. It's important that the keys are stable, predictable, and unique among siblings.

                                          
                                          class List extends React.Component {
      render() {
        const numbers = [1, 2, 3, 4, 5];
        const listItems = numbers.map((number) =>
          <li key={number.toString()}>{number}</li>
        );
    
        return (
          <ul>
            {listItems}
          </ul>
        );
      }
    }
    
                                          
                                        

    When using functional components, you can achieve the same result:

    Example:

                                          
                                          function List() {
      const numbers = [1, 2, 3, 4, 5];
      const listItems = numbers.map((number) =>
        <li key={number.toString()}>{number}</li>
      );
    
      return (
        <ul>
          {listItems}
        </ul>
      );
    }
    
                                          
                                        

    Keys should be assigned to the elements inside the array, rather than to the array itself.

    This helps React correctly identify and update each individual list item.