0% completed
In React, rendering lists of elements is a common task that is important for building dynamic user interfaces. List in React is commonly referred to as an Array (you can use them interchangeably).
Whether you're displaying a list of items fetched from an API or showing static data, React makes it easy to render lists efficiently.
React renders lists by looping over a collection of data and creating an element for each item. Due to the declarative nature of React, all you need to do is to describe the list structure. React handles the actual rendering of the lists and updates accordingly.
JavaScript's .map
function is used to iterate over an array and return a list of individual elements.
Here’s the general pattern:
function MyList(){ const items = ['Apple', 'Banana', 'Cherry']; return ( <ul> {items.map(item => ( <li key={item}>{item}</li> ))} </ul> ); };
In this component code:
<ul>
)..map
method iterates through the items array.<li>
element still wrapped inside a <ul>
.The key prop is an integral part of rendering lists in React. It helps React identify which items have changed, been added or removed. This ensures that the rendering process is more efficient.
Without a key, React would not be able to differentiate between elements and would prevent it from re-rendering the entire list every time it changes. This could result in unnecessary updates that negatively impacts performance.
Keys in lists must be unique and stable for each item.
On close examination of our previous example, the key prop of item would violate the rule of duplicate keys if there is more than one entry of an element.
For example, lets add an additional item of Apple to the list:
const items = ['Apple', 'Banana', 'Cherry', 'Apple'];
When React renders the list and goes through each list item, it encounters a duplicate value in the key props when it gets to the last element, Apple.
This automatically raises an issue in the rendering process and can cause React to misidentify elements during re-renders.
Using a Unique Identifier
To ensure that each key in the list is unique, it is recommended to use a unique identifier for each item. The unique identifier can be an index or a unique id.
Index is best suited for static data, while ID is better for dynamic data.
Using Index
This is how index is used in list rendering:
function MyList(){ const items = ['Apple', 'Banana', 'Cherry']; return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); };
Using id
This is how id is used in list rendering:
function MyList(){ const items = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' } ]; return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); };
Both methods follow the good convention of rendering lists and enables React keep track of items.
.....
.....
.....