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.
Using
JSX we can show lists using JavaScript's built-in Array.map()
method. The .map()
method is often used to take one piece of data and convert it to another.
In our scenarios, we are taking data and converting it to a piece of our view.
Let's
say we have a list of array
that we want to show in
a list:
This
component uses Array’s built-in map function
to create a new array newArr that
has the same number of elements, and where each element is the result of
calling the function you provide. The {}
brackets are used to render the array of
elements.
The
above is the shorthand code for write the map function. Since we
are not doing anything in the function's block body, we can also refactor it to
a concise body and omit the return statement and the curly braces for the
function body:
Rendering lists inside Components
So from the component’s point of view, we have to 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. We will discuss
about keys in detail in further articles. For now, let’s just assign a key to each of our list items in the above code.
Below is the example where we display the list of Objects with keys.
Display
Object List in React
Displaying
items from a list of objects in React is very simple. We can iterate over a
list of objects using the .map()
method in React JSX. Here is the
example in which we mapped a list of objects and displayed them in the React
app.
import React, { useState } from "react";
The key attribute is necessary for React to identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Since React uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we provided a unique id to every list item.