FrontEnd web
Published in

FrontEnd web

How to use a loop in React.js?
How to use a loop in React.js?

ReactJs ( intermediate level )

How to use loops in React.js?

Javascript comes with a bunch of loops, for example, for loop, for in, for of, while loop, do while, map(), and forEach().

The most common loops you see in reactjs map() and forEach(). Why do not people use different loops in reactjs?

In my article, You can learn how to use different loops like for loop, for in, for of and so on with react.js. I provide a loop taste with the same logic, and you cock loop according to your taste, and you can reuse it.

There are many ways to write the same code with different syntax and logic. You are sometimes stuck with the same logic, and you write the same code again and again. If you have a time, rethink and find better ways according to your project requirments.

Types

  1. For Loop
  2. For In
  3. For of
  4. While
  5. While do
  6. Map
  7. ForEach

These seven types of loops are used in javascript but in reactjs developer only use map() and forEach() loop.

You can check out all the code is available on GitHub here.

For Loop

For loops are the main loop and most common loop in javascript. But in react, you can't use it directly in reactjs like map(). Firstly you empty the array, and then, with help of for loop. it iterators on the array and push components( JSX) in an empty array and then use the empty array in return like I did with the result array.

    // for loop

const result = [];

for (let index = 0; index < data.length; index++) {

const element = data[index];

result.push(
<div className='mx-auto w-3/6 mt-10' key={element.id*3}>
<h2 className='text-xl'>{element.title}</h2>
<span className='text-md text-gray-500'>{element.author}</span>
<p className='text-md text-gray-600'>{element.description}</p>
</div>
)

}


// use it

return <div className='p-10'>

<h2 className='mt-2 text-center text-gray-800 text-2xl'> For loop</h2>

{result}

</div>;
}

For In

For in loop is used for the object, and the developer does not use a regular for loop with the object. For that reason for, in loop come with a picture, and you can use Iterators over the loop with any need of the Object.entries() method.

// for in
const results = [];

for (const property in objData) {

results.push(
<div className='mx-auto w-3/6 mt-10' key={property.id*5}>
<h2 className='text-xl'>{objData[property].title}</h2>
<span className='text-md text-gray-500'>{objData[property].author}</span>
<p className='text-md text-gray-600'>{objData[property].description}</p>
</div>
)

}

// use it

return <div className='p-10'>

<h2 className='mt-2 text-center text-gray-800 text-2xl'> For loop</h2>

{result}

</div>;

For of

With the common for loop, we use `array.length` to check the length of the array than for loop Iterators over the array. It is a lengthy process for developers. To solve this problem, for of loop come in the picture, you do not need count any length. For of loop automatically count length and Iterators over the array. It helps to write clean code.

// for in
const results = [];

for (const element of data) {

result2.push(
<div className='mx-auto w-3/6 mt-10' key={element.id*2}>
<h2 className='text-xl'>{element.title}</h2>
<span className='text-md text-gray-500'>{element.author}</span>
<p className='text-md text-gray-600'>{element.description}</p>
</div>
)
}

While

While loop is a traditional loop, and I never be use a while loop in my reactjs project. But It is interesting. you can use while loop in reactjs is like for loop. While is faster as compare to for loop in large scale of data. In large scale iteration I sugession to try while loop rather then for loop.

//  while loop

const result = []

let i = 0

while (i < data.length) {

const element = data[i];

results.push(
<div className='mx-auto w-3/6 mt-10' key={element.id*58}>
<h2 className='text-xl'>{element.title}</h2>
<span className='text-md text-gray-500'>{element.author}</span>
<p className='text-md text-gray-600'>{element.description}</p>
</div>
)

i = i + 1;

}

return (

<div className='p-10'>

<h2 className='mt-2 text-center text-gray-800 text-2xl'> while loop</h2>

{results}

</div>
);

While do

While do loop is run once and then check condition. for example in while do loop do statement block of code always run once and in end lastly check the condition.

But if you use while do loop in react you always check your code again rethink. without testing code never be go to production. Allways double check before deploy your react app with while do.


const result = []

let index = 0;



do {

const element = data[index];

result.push(
<div className='mx-auto w-3/6 mt-10' key={element.id*52}>
<h2 className='text-xl'>{element.title}</h2>
<span className='text-md text-gray-500'>{element.author}</span>
<p className='text-md text-gray-600'>{element.description}</p>
</div>
)


index = index + 1;

} while (index < data.length);

Map

Map is most comman loop method is people use in reactjs and it is famous in reactjs. Everybody use map() method in reactjs and it is recomeded by team team it self. It is easy to use map() in react. but map is create a disaster when we use map in nested loop for example map(item=>item.map()) it create code readbily and performance issue with large data set. allwyas use nested map combine with hook to handle permonce issue.

 data.map((item) => {
return <div className='mx-auto w-3/6 mt-10' key={item.id * 52}>
<h2 className='text-xl'>{item.title}</h2>
<span className='text-md text-gray-500'>{item.author}</span>
<p className='text-md text-gray-600'>{item.description}</p>
</div>
})

ForEach

You cant use forEach loop directly in side component like map() because map method return new array and forEcah does return a undefined. But you can use it following ways which i mention in the following code. it is fix ways for forEach.


const results = [];

data.forEach((item, index) => {

results.push(
<div className='mx-auto w-3/6 mt-6' key={item.id}>
<h2>{item.title}</h2>
<h4>{item.description}</h4>
<span>{item.author}</span>
</div>
);
});

return (
<div className='p-10'>

<h2 className='mt-2 text-center text-gray-800 text-2xl'> forEach loop</h2>

{results}

</div>
);

Tips

Nested loops is allwyas hurt the react performance. My suggestion is avoid the nested loops because it create code readability issue for team and secondly combine nested loops with reach hooks. For example you can use useMemo like it is helpful. But not for all case.

One think is remeber loop is comsume memory and ram. So always user carefully. for optimizion react app always break your app into small parts. for and while loop comes with break and continue statement it help to optimize app. It take time create or recreate app with for and while loop.

Do not work

Why forEach method is not work in Reactjs?

You can use forEach() directly in reactjs. because forEach() method undefind and map() method return new array.

function ArrayLoop(props) {

return (
<div className='p-10'>
{
data.forEach((item) => {
return <div className='mx-auto w-3/6 mt-10' key={item.id * 52}>
<h2 className='text-xl'>{item.title}</h2>
<span className='text-md text-gray-500'>{item.author}</span>
<p className='text-md text-gray-600'>{item.description}</p>
</div>
})
}
</div>
)

}

Why for loop is not work in Reactjs?

You can’t not use for loop in reactjs. because for loop return undefind.

function ArrayLoop(props) {

return (
<div className='p-10'>
{
for (const element of data) {

return <div className='mx-auto w-3/6 mt-10' key={element.id*2}>
<h2 className='text-xl'>{element.title}</h2>
<span className='text-md text-gray-500'>{element.author}</span>
<p className='text-md text-gray-600'>{element.description}</p>
</div>

}
}
</div>
)

}

Conclusion

You can use any javascript loops in reactjs, but some of the loops have restrictions and you don't use freely in reactjs; I try it some time it works fine, and in most cases, it converts the worst case and its effects directly on app performance.

You can share and follow us on Twitter and Linkedin. If you like my work, please read more content on the officialrajdeepsingh. dev, Nextjs, frontend web, and Sign up for a free newsletter.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rajdeep singh

JavaScript || Reactjs || Nextjs || Python || Rust || Biotechnology || Bioinformatic || Front-end Developer || Writer || https://officialrajdeepsingh.dev/