Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use For loop inside React JSX code

Tags:

reactjs

I am trying to fetch data in React JSX code using For Loop.

const count = 10

return (
    <>
        {for(let i = 0; i < count; i++) {
            return (
                <div>
                    <h1>{i}</h1>
                </div>
            )
        }}
    </>
)

I know I can use the map function in JSX without using for loop. But I'd like to figure this out using a for loop. I think we can use a for loop to get it to work and I hope anyone here can help me.

like image 681
Jack Avatar asked Oct 12 '25 17:10

Jack


1 Answers

When interpolating JSX, you need to either return JSX, or have the expression evaluate to an array where each element of the array is JSX.

For a for loop to work, you'd have to push to an array, then return that array at the end.

If you want to do it all inside the interpolated JSX:

return (
    <>
        {(() => {
            const arr = [];
            for (let i = 0; i < count; i++) {
                arr.push(
                    <div>
                        <h1>{i}</h1>
                    </div>
                );
            }
            return arr;
        })()}
    </>
)

But a more readable approach is to return the array itself, without putting it inside a fragment:

const count = 10;
const arr = [];
for (let i = 0; i < count; i++) {
    arr.push(
        <div>
            <h1>{i}</h1>
        </div>
    );
}
return arr;

But a for loop for this sort of situation is weird. The functional Array.from is better.

return Array.from(
    { length: 10 },
    (_, i) => (
        <div>
            <h1>{i}</h1>
        </div>
    )
);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!