cft
Become a CreatorSign inGet Started

List Rendering in React and the use of keys

List rendering can be very useful in designing great UI for our application and react supports great approaches for this purpose. In this article you will learn how List rendering works in react and the Dos and Don'ts of list rendering in react


user

Bishop ukpai

4 months ago | 9 min read
Follow

list-rendering-react-use-keys-epcdo

It is a common scenario to always want to place a list of items when building web applications UI. Examples of items that you can list could be a list of products, courses, or general items.

In react we can do a list of items without having to repeat our codes over and over. With this effect, our work becomes easier and even more fun-filled, because we do not need to manually list out items ourselves. In this article, I am going to walk you through everything you need to know on list rendering in react.

In this article, you will see the following sections

Outline

1)What is List rendering

2) Listing items in the UI with the map method

3)Lists and keys, why the use of keys is important

4 )Conclusion

What is list rendering in React?

List rendering in react is a mechanism that allows a developer to add a list of items in the UI of applications that they create. In react, developers have the option of using the array.map method in making this process a lot easier and more fun. If you have a good knowledge of JavaScript you should know that the with map method you can iterate through array list items applying the desired changes that you want on the list of items. For example, let's say we have a list of numbers in an, and we want to produce a new array that multiplies each number in the array by 3 and prints out the new output. Well, this is possible with the map method, all we have to do is create the array of numbers, and assign it to a variable, create another variable that will have the map method assigned to it as a value, and then print it, example the code below:

const array = [2, 3, 4, 6]

const map1 = array.map(x => x*3 )

console.log(map1)

The expected output from this should be 6, 9, 12, 18. if you check the console. With the map method, we were able to multiple through the array of numbers. This can also be applied in react because react is powered by JavaScript, so you can successfully run JavaScript codes in react. Now let’s see how we can implement this in listing items on the UI of our application.

Listing items on the UI with the map method in react

So far we have seen how the map method is implemented in JavaScript, what happens here is that the map method iterates through each item in the array and applies a specified function to each of the items, we can apply this in react to automatically list items on react application UI, to do this we have to implement these four simple steps

  1. Create a component

2) within the component define a variable, with an array list of items as a value

3) then include the map method in the return keyword.

So, let us see how this works. Create a new component file in the react application, you can call it “list.js”. In the list.js file let’s create the List component and the array list of names, so in the list.js file write out the code below

import React from 'react'

const List = () =>{

const name = ['Bella', 'Favor', 'Treasure']

return(

)}

export default List

Then import and render the List component in the App.js file. we can list out each of the array using the array list’s index by adding the code below inside the return statement and we should see the items we have in the array displayed on the browser

<div>

<h1>{name[0]}</h1>

<h1>{name[1]}</h1>

<h1>{name[2]}</h1>

</div>

Well great, this worked perfectly well and you might be thinking well I should just stick to this method. You are excited now because you only have three items in the array, even with only three items in the array, you can see that it is quite tedious to implement this method, what if you have up to 20 or even 30 items or hundreds of items in the array, then you should know that this method won’t be useful at this point, a better way of doing things is through the use of the array map method, so instead of listing each item one after the other in the component, we can just use the map method and set a specific function that lists out every item in the array. So, clear out the h1 tag and add the code below in the div tag

{name.map(name =><h1>{name}</h1>)}

If you save the file and take a look at the browser you should see all the items in the array listed out, by this, we have just reduced our code and achieved something great.

You can also have an array list with objects properties. For example, let’s say you want to have a person object that person should have a name, age and may and id. We are creating an array, but this time it should have an object property pass into it. Your name variable code should look like this now

const name = [{name:'Bella', age: 16, id: 3}]

Let’s call it person since the object inside describes a person, so change the variable name to persons. With this we have just described a person variable with objects that describes a person, we can also pass another set of object property, we can pass as many objects as possible, so let’s go ahead and add two more objects so add the code below in the array

{name:'Favor', age:19, id:2},

{name:'Favor', age:15, id:1}

Your code should look like this

[{name:'Bella', age: 16, id: 3},

{name:'Favor', age:19, id:2},

{name:'Treasure', age:15, id:1}]

You can access any item in the array with the map method, we simply use the array.map method and inside the array we call the person.key to display the value of the key in the browser, so write the code below in the return statement

{person.map(person =><h1>{person.name}</h1>)}

Now if you save the file and head over to the browser, you should see “Bella”, “Favor” and “Treasure” displayed, this is because we accessed the name, so if we want to access the id or the age, we simply person or person.age, and this will either show the age or id in the browser, with this effect we have successfully displayed items on the browser using the map method, but there is still another problem that we need to resolve. Although we were able to display contents on the browser successfully, if you open up the console, you will notice that there is an error message that reads “Each child in a list should have a unique key prop”, so you might be wondering what this means. Well, we will talk about this in the next section of this article.

List and keys (why the use of keys is important)

From the last section, we discovered that when we looked at the console, we saw an error message, well this message simply means that react is trying to warn us that each item in the list should have a key prop and the value of the key prop should be unique. Essentially, no two items should have the same key value prop, but how do we create this prop? A key can have a value of any type it can be a string, number, or anything data, provided that this value is unique.

From our example, we can set the value of the key to be equal to the name property of the array. Back in VScode, we can add the key prop inside the opening h1 tag and assign the value of the name property to it with the line of code below

key={person.name}

If you save the file and refresh the page in the browser, you will notice that the warning message is gone, this is because, the name of each item is unique, but what if we decided to add a fourth person object, with the name set to “Bella” and age of say 20 and an id of 4, so if you save the file and head over to the console, you should see the warning message again, because the key is no longer unique, this is a common scenario because you can have two items with the same name value in your list while programming, one way to solve this is by making use of the I because all the ids are unique here, so in place of name, put id and that will solve the problem.

Another way you can solve the key prop problem is through the use of indexes as keys. Maybe you have just an array of items, without ids like the first array we created, that is an array with an object property passed into it, well you can also have a key prop for the list of items, this time the value of your key would be the index of the element. Clear out the objects in the array, and add only the names “Bella”, “Favor” and “Treasure”, so your array should look like this:

const person = ['Bella', 'Favor', 'Treasure']

The next step is to add index as a second parameter within the render method body and then pass it as the key-value like this

{person.map((person,index) =><h1 key={index}>{person}</h1>)}

Now if you save the file and head over the browser you will see that the error message is gone. In as much as the index can be used key-value value, it also comes with its type of error, and should not be the first option all the time. The index as a key approach should be used only when your application satisfies the following conditions

1)     When there is no unique id for items in the list

2)     If the list is going to remain static and won't change, for example, if you are not going to add to the list or remove any item from the list

3)     If reordering won’t be done in the list

If all three criteria are satisfied then you can apply the index as a key approach, otherwise, just stick to the use of ids.

Keys help react to identify what item was changed added or removed from the list, this helps and plays a crucial role in handling UI updates efficiently. Let’s take into consideration a list of items like we have in our array, if we try to add a new item into the list, what react does is that it iterates through both lists at the same time and generates a mutation whenever there is a difference. In our example when react matches the first item sit sees that there is no difference, it continues to the second item and also there is no difference, and also the third item, but when it gets to the fourth item, it seems that there is a difference and then it includes the new item inside the DOM tree. Imagine we try to add this new item at the top, react checks the entire items and sees that everything is now different, this will result in tearing down the entire tree and modifying every item and this can be a problem, so to solve this, react supports the use of keys. When children in the list have keys, these keys are used for matching children in the original tree with the ones in the new tree. So, if you add the fourth item to the list with a key, then react will know that the element with that unique was just added and it would be placed in the appropriate position without having to tear down the entire tree and building from scratch. So, at all times try to apply the key prop when listing out items in react

Conclusion

In summary the use, of the list rendering method is something developers can not omit most of the time when they build UI, in one way or the other you must have a list of items in the browser.

With react listing of items just got easier and better with the use of the array map method, so instead of having multiple lines of code that list out each item, we simply pass in a function that lists out each item in the array

In this article we saw how we can make use of this method and possible problems that could arise from listing items, we also went through how to solve this problem and some best practices that we can keep to while working with the listing.

Upvote


user
Created by

Bishop ukpai

Follow

I am a software engineer


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles