Table of contents
1.
Introduction
2.
Using for loop in react js 
2.1.
for(standard)
2.2.
for-of
2.3.
for-in
3.
Need of for loop in react js 
4.
Working of For Loop in react js
4.1.
Filter() function in react js
5.
Frequently Asked Questions
5.1.
Can you use a for loop in React?
5.2.
How do you loop a function in React?
5.3.
What are the advantages of for loop in react.js?
6.
Conclusion
Last Updated: Oct 29, 2024
Easy

For Loop in React JS

Author Vidhi Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In React JS, when repetitive tasks need to be executed multiple times until a certain condition is met, developers often utilize loops. Loops are fundamental programming constructs that iterate over a block of code repeatedly, altering it each time based on specified conditions. While React JS itself does not have built-in loop structures like traditional programming languages such as JavaScript, developers can still implement loop-like behavior using JavaScript constructs within React components. 

For Loop in React JS

In this article, we will discuss for loop in react js.

Also See, Dropdown in React JS, Hooks in React JS

Using for loop in react js 

In React JS, developers often leverage the power of JavaScript's for loop within components to iterate over arrays or collections of data and dynamically render elements. This will become more clear from the following example: 

<ul>
	<li>one</li> 
	<li>two</li> 
	<li>three</li> 
</ul>

 

Now, let’s say, we add another element ‘four’ into this list. For doing this, React will change each element instead of keeping the elements- <li>one</li>, <li>two</li>, and <li>three</li>  intact. This creates inefficiency.
Keys are used to overcome this. Consider the following:

<ul>
	<li key=’one’>one</li> 
	<li key=’two’>two</li> 
	<li key=’three’>three</li>  
</ul>

 

Now, if  ‘four’ is added as following:

<li key=’four’>four</li> 

 

The whole list will not be created again instead, just the new element will be added, making the whole process less time-consuming and more efficient. 

For this blog, this much understanding of keys is sufficient.
This whole updation and inserting of elements will become more clear if you understand the concept of React Reconciliation in react js.

Now let us understand for loop in react js.

for(standard)

It is used as any other for loop, similar to other programming language like this:

const arr=['One','Two','Three','Four'];
export default function App() {
const for_loop = []
for (let i=0;i<arr.length;i++) {
  for_loop.push(<li>{arr[i]}</li>);
};
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    {for_loop}
  </div>
)}

Output:

 

Providing keys for elements in react js can be done as follows:

const arr=['One','Two','Three','Four'];
export default function App() {
const for_loop = []
for (let i=0;i<arr.length;i++) {
  for_loop.push(<li key={i.toString()}>{arr[i]}</li>);
};
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    {for_loop}
  </div>
)}

 

Here, the element’s value is used as the key itself. But, in case you want you can specify any key of your choice. 

for-of

In this kind of for loop in react js, every element is iterated by considreing it as a part of the array like this:

const arr=['One','Two','Three','Four'];
export default function App() {
 const for_of = []
 for (let item of arr) {
   for_of.push(<li>{item}</li>);
 }
 return (
   <div>
     <center><h1>Hello Ninja!</h1></center>
     {for_of}
   </div>
 )} 

 

It produces the thing on the screen. 

Providing keys for elements in react js can be done as follows:

const arr=['One','Two','Three','Four'];
export default function App() {
const for_of = []
for (let item of arr) {
  for_of.push(<li key={item.toString()}>{item}</li>);
};
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    {for_of}
  </div>
)}

for-in

In this kind of for loop every element is accessed by its index in react js like this:

const arr=['One','Two','Three','Four'];
export default function App() {
const for_in = []
for (let item in arr) {
  for_in.push(<li key={item.toString()}>{arr[item]}</li>);
};
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    {for_in}
  </div>
)}

 

There is no change in the output. It remains the same.
Keys for elements in react js can be mentioned as follows:

const arr=['One','Two','Three','Four'];
export default function App() {
const for_in = []
for (let item in arr) {
  for_in.push(<li key={item.toString()}>{arr[item]}</li>);
};
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    {for_in}
  </div>
)}
map()

 

map() is the most famous way of iteration through the arrays. It is the most widely used way used. map function returns JSX. It uses a key. It stores data in form of pairs. This method forms a new array by calling a function on every element in the calling array. In case, no function is passed, it uses the original element.

const arr=['One','Two','Three','Four'];
export default function App() {
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    <ul>
    {arr.map((item) => (
      <li key={item.toString()}>
      {item}
        </li>
    ))}
   </ul>
  </div>
)}

 

Usually, developers use map() only. It is very rare that any other function is used.  

Need of for loop in react js 

Let us suppose that there is an array as follows:

const arr=[‘One’, ’Two’, ’Three’, ’Four’]; 

 

Declaring such an array in react js can be done in the following way:

const arr=['One','Two','Three','Four'];
export default function App() {
 return (
   <div>
     <h1>Hello Ninja!</h1>
   </div>
 )} 

 

It will just show the text in the h1 tag. 

 

Now, you want to print each element of the array in react js. A very technique to do so in react js is as follows: 

const arr=['One','Two','Three','Four'];
export default function App() {
 return (
   <div>
     <center><h1>Hello Ninja!</h1></center>
     <ul>
       <li>{arr[0]}</li>
       <li>{arr[1]}</li>
       <li>{arr[2]}</li>
       <li>{arr[3]}</li>
     </ul>
   </div>
)}

 

Output:

 

This works fine. The array of elements is also printed on the screen as wanted. But, in case you add more elements to the array, then in order to print more elements, more code has to be written. That is, each element needs to be printed separately. 

Assume a real-life scenario where the array contains the names of users and shows it on the site. So, every time a new user comes, manually a new state element would have to be added to print his name. That is such a time-taking and tedious task. 
This is where loops are useful. They can iterate over all the elements of the array or list in one go without writing much code.  

Let us now see the usage of for loop in react js. 

Working of For Loop in react js

In React JS, the for loop itself works similarly to how it works in standard JavaScript. However, when using for loops in React components, it's essential to understand how React handles rendering and updates.

  1. Initialization: Like in traditional JavaScript, a for loop in React begins with an initialization statement. This statement typically initializes a loop counter variable.
  2. Condition: The loop continues executing its body as long as the specified condition remains true. This condition is evaluated before each iteration of the loop.
  3. Iteration: After each iteration, the loop counter is updated according to the iteration statement. This statement typically increments or decrements the loop counter.
  4. Rendering JSX: Within the loop body, JSX elements are generated dynamically based on the loop iteration. These JSX elements can represent components, HTML elements, or any other React elements.
  5. Key Prop: When rendering arrays of elements in React, it's crucial to provide a unique key prop to each rendered element. This helps React efficiently update the DOM by identifying which elements have changed, been added, or been removed.
  6. Component Rerendering: In React, when the state or props of a component change, React automatically rerenders the component to reflect these changes. When using a for loop to render elements, React intelligently compares the new JSX elements with the previous ones to determine the minimal set of changes required to update the DOM.
  7. Optimization: While for loops can be used to generate dynamic content in React, it's often more idiomatic to use array methods like map() for rendering lists. Array methods provide a more declarative syntax and often result in cleaner and more maintainable code. Additionally, React's reconciliation algorithm is optimized for array methods, making them more efficient in many cases.

Filter() function in react js

The filter() function can be used to segment out items before they are rendered along with map. For example, in the below code only ‘One’ and ‘Three’ elements will be rendered.

const arr=['One','Two','Three','Four'];
export default function App() {
return(
  <div>
    <center><h1>Hello Ninja!</h1></center>
    {arr.filter((item) =>(item.includes('e'))).map((item)=><li key={item.id}>{item}</li>)}
     // Filter out elements that do not contain ‘e’ character
  </div>
)}

 

Check out Advantages of React JS here.

Frequently Asked Questions

Can you use a for loop in React?

Yes, you can use a for loop in React components to iterate over data and dynamically render elements.

How do you loop a function in React?

You can loop a function in React by using JavaScript's for loop or array methods like map().

What are the advantages of for loop in react.js?

Advantages of for loop, in general, include:

  • It offers code re-usability.
  • Makes the code compact.
  • Traversing becomes easy following a condition

Conclusion

This article covers for loop in ReactJS, with its need and uses.

We hope that this blog has helped you understand the concept better, and if you would like to learn more, check out our articles on Coding Ninjas Blogs

Recommended Raeding: Characteristics of OOPS

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSQLSystem Design, and many more!
You can also consider our React Js Course to give your career an edge over others.

Do upvote our blog to help other ninjas grow. 

Happy Coding!      

Live masterclass