DEV Community

Arc Coder | Harsh Patel
Arc Coder | Harsh Patel

Posted on

For Loop in JavaScript / ReactJS

A for loop can not be used directly in the JSX block. So we can not use it inside the return block.

So we have to make a function for that. The function can either be it the main functional block or the custom function made inside the main function. Here I've used the main App function block only.

export default function App() {
    const items = [];

    for (var i = 0; i < 20; i = i + 3) {
        const itemsArr = [];
        for (var j = i; j < i + 3; j++) {
            itemsArr.push(<span>{j}</span>);
        }
        items.push(<div>{itemsArr}</div>);
    }

    return items;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)