Sobes.tech
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:

  1. Using the map method to iterate over the array elements.
  2. For each element in the array, returning an instance of the desired component.
  3. Passing a unique key prop 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:

  • items is an array of data.
  • map iterates over the array.
  • ItemComponent is 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.