DEV Community

SavvyShivam
SavvyShivam

Posted on

List in React

List in React

Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to do this in detail further in this article.
Let’s first see how we can traverse and update any list in regular JavaScript. We can use the map() function in JavaScript for traversing the lists.

In the above program the array “numbers” is getting traversed one by one and each element is incremented by 1. The list then is finally returned in the form of unordered lists.

Output

Rendering lists inside Components

In the above code in React, we had directly rendered the list to the DOM. But usually this not a good practice to render lists in React. Consider the example of a Navigation Menu. In any website any navigation menu will not be hard coded. This item is fetched from the database and then displayed as lists in the browser. So from the component’s point of view, we can say that we will pass a list to a component using props and then use this component to render the list to the DOM. We can update the above code in which we have directly rendered the list to now a component that will accept an array as props and returns an unordered list.

You can see in the above output that the unordered list is successfully rendered to the browser but a warning message is logged to the console.

Warning: Each child in an array or iterator should have a unique “key” prop
The above warning message says that each of the list items in our unordered list should have a unique key. A “key” is a special string attribute you need to include when creating lists of elements in React.
The above code is written in the given sandbox link :
https://codesandbox.io/s/introduction-lists-xgp802

https://codesandbox.io/s/introduction-lists-xgp802

Top comments (0)