Junior
How to render components based on an array?
sobes.tech AI
Answer from AI
Rendering components based on an array in React is usually done using the map method.
The process involves the following steps:
- Using the
mapmethod to iterate over the array elements. - For each element in the array, returning an instance of the desired component.
- Passing a unique
keyprop to each rendered component for React's optimization.
Example with a functional component:
import React from 'react';
const ItemComponent = ({ data }) => (
<div>
<p>{data.text}</p>
</div>
);
const ListComponent = ({ items }) => (
<div>
{items.map(item => (
<ItemComponent key={item.id} data={item} /> // Unique key is required
))}
</div>
);
In this example:
itemsis an array of data.mapiterates over the array.ItemComponentis rendered for each element.key={item.id}is used to identify each element in the list.
It is important to remember the necessity of a unique key for each element in the list. This helps React efficiently update the DOM when changes occur in the array. The key should be a unique identifier of the element (e.g., an ID from a database), rather than the index in the array, especially if the order of elements can change.