Working with Lists in React

react lists tutorial
10 November 2024

When working with lists in React, it's important to use JSX and the concept of keys when rendering lists is clear. In React, to display a collection of data as a list, the map method available in JavaScript is used. By using this method, you can generate JSX elements from the data and convert this array to a list of JSX elements.

Suppose you have an array of names and want to display these names as a list for the user. This task is very simple; it's enough to convert this array into a collection of

  • in HTML using the map method. Each of these
  • elements must contain a key so that React can efficiently identify each type of modification or update in the data.

    Using keys in lists is another concept of optimization that has its own specific uses. When a key property is specified in JSX, React can directly associate the changes made to specific elements of the list and indicate this topic as particularly important in effective user interaction. Therefore, when rendering lists, you should always ensure that each element has a unique key.

    Keys are usually a unique piece of data such as an ID used in the array. If there is no unique ID, you can use the index of each element in the array; however, this method is not recommended unless no other unique identifiers exist as using indices can lead to issues in some scenarios.

    Example Code for Working with Lists in React

    
    <ul>
    {names.map((name, index) => (
    <li key={index}>{name}</li>
    ))}
    </ul>

    Code Explanation

    <ul>
    Create an unordered list for displaying a list of names
    {names.map((name, index) =>
    The map method in JavaScript is called on the names list, and for each element, a JSX element is returned
    <li key={index}>
    Create a list item element for each name and assign a key using the index
    {name}
    Use the name in JSX for display
    </li>
    Close the list item tag
    </ul>
    Close the unordered list tag
  • FAQ

    ?

    Why should I use keys?

    ?

    What should a key look like?

    ?

    Can I use indices as keys?