How to use Traditional Loop In ReactJS

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.

Syntax:

for (initialization; condition; increment/decrement) {
// code
}

Example: The below example uses traditional Loop to Loop inside React JSX.

JavaScript
import React, { useState } from 'react';

const App = () => {
    const [colors, setColors] =
        useState(['red', 'green', 'blue']);

    const approach2Fn = () => {
        const newColor = prompt('Enter a color:');
        if (newColor) {
            setColors([...colors, newColor]);
        }
    };
    const colorItems = [];
    for (let i = 0; i < colors.length; i++) {
        colorItems.push(
            <div key={i}
                style={{
                    backgroundColor: colors[i],
                    padding: '10px', margin: '5px',
                    borderRadius: '2px', width: '100px'
                }}>
                {colors[i]}
            </div>
        );
    }
    return (
        <div>
            <h1 style={{ color: 'green' }}>
                w3wiki
            </h1>
            <h3>Using Traditional Loop</h3>
            <div>{colorItems}</div>
            <button onClick={approach2Fn}>
                Add Color
            </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....