React Loop Rendering: Map Components Guide

In React, looping through rendering components can be achieved by using the map method of an array. The specific steps are as follows:

  1. First, create an array containing the data of the components that need to be rendered.
  2. Traverse the array using the map method, returning a component instance for each element and storing it in a new array.
  3. Finally, render the component instances stored in the new array onto the page.

The sample code is as follows:

import React from 'react';

const ComponentList = () => {
  const data = [1, 2, 3, 4, 5];
  
  return (
    <div>
      {data.map(item => (
        <Component key={item} data={item} />
      ))}
    </div>
  );
};

const Component = ({ data }) => {
  return <div>{data}</div>;
};

export default ComponentList;

In the example above, the ComponentList component uses the map method to loop through the data array, returning instances of the Component component, storing them in a new array, and finally rendering the component instances from the new array onto the page.

bannerAds