How to use Array.map( ) Method In ReactJS

In this approach, we are using Array.map() inside JSX to dynamically render a list of numbers from the state array numbers. Each number is displayed as an <li> element with inline styling for color, margin, and cursor. The approach1Fn function adds a random number to the list when the “Click Me” button is clicked, demonstrates dynamic rendering and user interaction within React JSX.

Syntax:

array.map((currentValue, index, array) => {
// code
}, thisArg);

Example: The below example uses Array.map() to Loop inside React JSX.

JavaScript
// App.js

import React, { useState } from 'react';

const App = () => {
    const [numbers, setNumbers] =
        useState([1, 2, 3, 4, 5]);
    const approach1Fn = () => {
        const randomNum =
            Math.floor(Math.random() * 10) + 1;
        setNumbers([...numbers, randomNum]);
    };
    return (
        <div>
            <h1 style={{ color: 'green' }}>
                w3wiki
            </h1>
            <h3>Looping with Array.map()</h3>
            <ul>
                {numbers.map((number, index) => (
                    <li key={index}
                        style={{
                            marginBottom: '10px',
                            color: 'blue',
                            cursor: 'pointer'
                        }}>
                        Number {number}
                    </li>
                ))}
            </ul>
            <button onClick={approach1Fn}>
                Click Me
            </button>
        </div>
    );
};

export default App;

Output:

Loop Inside React JSX

When working with React, you often need to render lists of items dynamically. JavaScript’s map function provides a convenient way to loop through arrays and generate JSX elements for each item. In this article, we’ll explore how to loop inside JSX in React using various techniques and best practices.

Prerequisites

Similar Reads

Steps to Create React Application

Step 1: Create a React application using the following command:...

Using Array.map( ) Method

In this approach, we are using Array.map() inside JSX to dynamically render a list of numbers from the state array numbers. Each number is displayed as an

  • element with inline styling for color, margin, and cursor. The approach1Fn function adds a random number to the list when the “Click Me” button is clicked, demonstrates dynamic rendering and user interaction within React JSX....

  • Using Traditional Loop

    In this approach, a traditional for loop is used within JSX to dynamically render colored div elements based on the colors array. The loop iterates through the colors array, generating div elements with inline styling for each color. Users can add new colors to the list using the approach2Fn function, demonstrating dynamic rendering and user interaction within a React component....