Course Content
React Mastery
React Mastery
Rendering a Data Collection
When working on modern web apps, it is common to render collections of data received from the backend. To accomplish this, we utilize the map()
method. Within the map()
method, we employ a callback function and return JSX to render the desired output.
Let's take an example to illustrate how it works. We will have an App
component that will pass the prop toys
, an array of objects. The ToyCard
component will utilize the map()
method to render each toy in the array.
In lines 13-15, we observe the utilization of the map()
method. It allows us to iterate through each item in the array, extract its value, and generate specific markup based on the data of each item.
Full app code:
However, if we pay attention to the console, we can find out that we get the warning: Each child in a list should have a unique "key" prop.
.
Key
The key is a crucial string prop that must be assigned when creating elements within a collection.
React utilizes keys to ensure a stable identity for elements within a collection. These keys allow React to identify which elements must be re-rendered and re-created when changes occur rather than recreating the entire collection. Using keys prevents unnecessary re-creation of elements, leading to improved performance.
Note
The key must be unique among neighboring elements. It should remain constant and not change over time.
It is commonly recommended to utilize identifiers, such as id
values from backend data, as key props. This practice allows React to effectively identify and manage individual elements within a collection.
Let's fix our previous app using the key props for the items:
Line 14: the key
prop is set on the element that will be rendered multiple times within an array of data.
Full app code:
Thanks for your feedback!