4

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.

1 Answer 1

24

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>
    )
);
Sign up to request clarification or add additional context in comments.

1 Comment

This Array.from solution rocks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.