React Array Loop

In React, rendering lists or arrays is a common task, especially when dealing with dynamic data. Using JavaScript’s map() method, you can loop through arrays and generate elements for each item, making your UI dynamic and efficient.


How to Loop Through Arrays in React

React leverages JavaScript’s map() function to iterate over arrays and create components or elements for each item in the array. The map() method returns a new array of React elements which can then be rendered within your component.


Steps to Loop Through Arrays

  1. Create an array of data.
  2. Use the map() function to iterate over the array.
  3. Return a React element for each item.
  4. Ensure each item has a unique key prop for optimal rendering performance.

Example 1: Rendering an Array of Strings as List

In this example, we take an array of strings, and display them as a list in UI.

App.js

</>
Copy
import React from 'react';

function App() {
  const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

  return (
    <div>
      <h1>Fruit List</h1>
      <ul>
        {fruits.map((fruit, index) => (
          <li key={index}>{fruit}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Output: