DEV Community

Cover image for Rendering Lists in React
Tejeshwer Singh Sachdeva
Tejeshwer Singh Sachdeva

Posted on

Rendering Lists in React

A common scenario while working on a website is to render a list of items, and that might be your follower's list, notes in a todo app, contact list, or any kind of a list. In a simple static HTML site, we use the <ul> or <ol> tag along with the <li> tags to render the list based on whether it is unordered or ordered respectively. But in today's article, we'll dive into the rendering list with ReactJS.
As we all know that ReactJS unlike other frameworks is JavaScript centric which means that it allows us to use inbuilt JavaScript functions, keywords, and classes to apply functionalities to our web page. For rendering a list of items of our web app we can use the existing JavaScript map() method.
What our map() method will do is that it will iterate over our array/list of items, take each item and perform some task on it and return the update state or UI for our application. Below is an example of how to use the map() method within a React component.

function ListRendering() {
    const avengers = [ 'Iron Man', 'Captain America', 'Hulk', 'Thor', 'HawkEye'];

    return (
        <div>
            <h1>My Avenger List</h1>
            <ul> 
                { avengers.map( avenger => <li>{avenger}</li> }
            </ul>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

We can further optimize our markup by storing the resultant markup returned from the map method and then rendering it within our return statement, just like we did with the conditional rendering example. Here's how to do it:-

function ListRendering() {
    const avengers = [ 'Iron Man', 'Captain America', 'Hulk', 'Thor', 'HawkEye'];
    let avengerList =  avengers.map( avenger => <li>{avenger}</li>

    return (
        <div>
            <h1>My Avenger List</h1>
            <ul> 
                { avengerList }
            </ul>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Keys in React List Rendering

If we ran the above examples in our browser we might get an error in our console which says: " Warning: Each child in an array or iterator should have a unique key prop ".

a.png
This is one of the most common errors that show up while using react.
What this error means is that in react whenever we render an item using the map() method or through any other iteration, it should have a key prop and the value of the key prop should be unique for each item in the list. Now, why do we need the key prop?
We need a key prop because it helps react in finding which item/items in the list have been modified, updated, removed, or added, and through the key prop, react handles the UI updates efficiently. Let's take an example of what will happen when we render a list in React without using a key prop.

<ul>
    <li>Iron Man</li>
    <li>Captain America</li>
    <li>Thor</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Let's now imagine we have added some functionality for the user to add a new item at the beginning of the list, and using that user enters 'Hulk' to our list. Now our updated list would be.

<ul>
    <li>Hulk</li>
    <li>Iron Man</li>
    <li>Captain America</li>
    <li>Thor</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

It might look fine but what has happened is that react compares each item in the current list to the previous one, example 'Hulk' in the updated list will be compared to 'Iron Man' in the previous list, and as the values are changed React will re-render the whole list rather than just render the new item 'Hulk'. This is why keys are used for the efficient handling of lists in our React app.
Let's take an example of how to add keys to our list:-

function ListRendering() {
    const avengers = [ 
                                      { 
                                        id: 1, 
                                        name: 'Iron Man'
                                       }, 
                                      { 
                                        id: 2, 
                                        name: 'Captain America' 
                                      }, 
                                      {  
                                        id: 3, 
                                        name: 'Hulk' 
                                       },
                                       { 
                                         id: 4, 
                                         name: 'Thor' 
                                       }, 
                                       { 
                                          id: 5,
                                          name: 'HawkEye'
                                       }
                                     ];
    let avengerList =  avengers.map( avenger => <li key={ avenger.id }>{avenger.name}</li>

    return (
        <div>
            <h1>My Avenger List</h1>
            <ul> 
                { avengerList }
            </ul>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

An important point to note here is that keys in React are reserved and cannot be used within the JSX of our child component.

In a case when a unique id or some other unique value is not present in our array/list we can also use the index as a key to preventing ourselves from the error in the console, but while adding new items to the start of the list the problem will still persist similar to the condition when we had no key, this can be because by default React uses the index as the key.
But still, we can use the index as key if and only if:

  1. Items do not have a unique value.
  2. List is static.
  3. List won't be filtered or re-ordered.

Top comments (0)