DEV Community

Cover image for Loops in React JSX: A deep dive into the basics
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

Loops in React JSX: A deep dive into the basics

Loops are basically iterative statements that are used to repeat actions until a condition is met. These are important because they can perform operations within seconds while reducing long lines of code. They help developers with code reusability and accelerate processes by traversing various data structure elements, such as linked lists or arrays.

Almost every language today supports the Loops concept, and these play a critical role while learning bespoke software development.

In this blog, we will learn the fundamentals of Loops in React JSX, and how they are used practically. We will also look at JavaScript XML (JSX) and how to use methods like the map function loop inside React JSX and render a list of items.

If you are a ReactJS developer or have worked with React, you probably have heard the term "JSX." It is essentially a JavaScript syntactic extension used for producing markup using React.

Planning to hire dedicated ReactJS developers? Connect us now.

What exactly is JSX?

JSX is just a JavaScript syntax extension, and it stands for JavaScript XML. We can write HTML code directly in React within JavaScript code. You can construct a template with React using JSX, and it comes with complete JavaScript capabilities rather than just being a simple template-building language.

It is faster than normal JavaScript because it performs optimization while converting to normal JavaScript. Instead of separating the markup and logic into separate files, ReactJS uses components for this purpose. You can check out this detailed tutorial on React components vs elements

Remember, JSX will not work directly in browsers and requires a build process to convert JSX standards into React.createElement function calls.

To help you understand clearly, here is an example of JSX:

Standard JSX


const handleButton = () => {
    alert('Hello, Welcome to loop Tutorial')
  }

  return<div><button onclick="{()" title="submit"> handleButton()}>Click Me</button></div>

Enter fullscreen mode Exit fullscreen mode

Read More: A step-by-step guide on using Redux Toolkit with React

This JSX will be converted to something like this -

App.js

import React from 'react'
function App() {
  const handleButton = () => {
    alert('Hello, Welcome to loop Tutorial');
  };

  return React.createElement(
    "div",
    null,
    React.createElement(
      "button",
      {
        title: "submit",
        onClick: () => handleButton()
      },
      "Click Me"
    )
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, we used React.createElement to create a button in React.js. The output of the above code is shown below.

Image description

How to render loops in React JSX?

Loops offer a quick and easy way to accomplish something repeatedly. You may perform repeated tasks in seconds by setting conditions to satisfy. Now the question is how to render loops in React JSX. To address this, we will look at 5 different forms of loops used to render elements in React JSX.

Loops in JSX:

1) Map:

You can iterate over an object using the map method. You can use this method to render the same component again and again. Let’s understand by an example.

Assume we need to display a list of users every time we construct a < li >component. Instead, I use the map function to create the < li > element many times.

import React from 'react'
const App = () => {
  const user = ['Rahul', 'Shivam', 'Ayesha', 'Akash', 'Poonam'];
  return<div><ul><li>
      {
        user.map((names,i) => {
          return</li><li key="{i}">{names}</li><li>
        })
      }</li></ul></div>
}
export default App;

Enter fullscreen mode Exit fullscreen mode

You may have observed that we did not generate < li > elements 5 times. We iterated the array with a map, and the map returned the new element. The output will be as follows:

Image description

2) For

Users can use the standard “for” loop for creating the

  • element. Here you have to use the length function for giving the last point of the loop.
    import React from 'react'
    const App = () => {
      const users = [
        { id: 1, Name: 'Rahul' },
        { id: 2, Name: 'Shivam' },
        { id: 3, Name: 'Ayesha' },
        { id: 4, Name: 'Akash' },
        { id: 5, Name: 'Poonam' }
      ];
    
      const displayUser = (users) => {
        let name = [];
        for (let i = 0; i < users.length; i++) {
          name.push(<li key="{i.toString()}"> {users[i].Name}</li>)
        }
        return name
      }
      return<div><ul><li> {displayUser(users)}</li></ul></div>
    }
    export default App;
    
    

    3) For-in

    The For-in loop allows you to iterate through value and property. Let's look at an example of how to utilize a For-in loop.

    import React from 'react'
    const App = () => {
      const users = [
        { id: 1, Name: 'Rahul' },
        { id: 2, Name: 'Shivam' },
        { id: 3, Name: 'Ayesha' },
        { id: 4, Name: 'Akash' },
        { id: 5, Name: 'Poonam' }
      ];
    
      const displayUser = (users) => {
        let name = [];
        for (let idx in users) {
          const item = users[idx];
          name.push(<li key="{item.id}">{item.Name}</li>)
        }
        return name
      }
      return<div><ul><li> {displayUser(users)}</li></ul></div>
    }
    export default App;
    
    

    4) For-of

    For-of loop lets you loop over iterable data structures such as arrays, maps, strings, etc. Let’s understand it with an example.

    import React from 'react'
    const App = () => {
      const users = [
        { id: 1, Name: 'Rahul' },
        { id: 2, Name: 'Shivam' },
        { id: 3, Name: 'Ayesha' },
        { id: 4, Name: 'Akash' },
        { id: 5, Name: 'Poonam' }
      ];
    
      const displayUser = (users) => {
        let name = [];
        for (let item of users) {
          name.push(<li key="{item.id}">{item.Name}</li>)
        }
        return name
      }
      return<div><ul><li> {displayUser(users)}</li></ul></div>
    }
    export default App;
    
    

    5) Filter

    When we have to apply a condition to records and then show the filtered record using a loop, we must use the filter and map methods both at the same time, which is known as the "chaining technique." The filter will yield a new array, and we will apply the map function to the new array.

    import React from 'react'
    const App = () => {
      const users = [
        { id: 1, Name: 'Rahul' },
        { id: 2, Name: 'Shivam' },
        { id: 3, Name: 'Ayesha' },
        { id: 4, Name: 'Akash' },
        { id: 5, Name: 'Poonam' }
      ];
      return<div><ul><li>
          {
            users
              .filter((user) => user.Name.includes('m'))
              .map((item) => {
                return</li><li key="{item.id}">{item.Name}</li><li>
              })
          }</li></ul></div>
    }
    export default App;
    
    

    While learning all these loops, you might have noticed a ‘key’ property used in the

  • element. You're probably wondering why we utilized it here. What is its significance? Let’s discuss it.

    Importance of key in the loop

    The Key property in ReactJS is used to determine whether any elements have changed, which elements have been added, and which elements have been removed. If we do not use the key, you will get one warning in the console. Check out the image given below.

    Image description

    Normally, the index is used as a key. However, the use of the index as a key has a detrimental influence on the performance of a React App. React officially recommends using string as a key.

    Conclusion

    Loops are crucial subjects to master for every developer since they help them reduce a lot of repetitive work, especially when iterating through numerous data and data structures. In this blog, we learned what a loop is, the types of loops in React-JSX, and how each of them helps to reduce load realistically. We've also seen the significance of a key element and the consequences of not employing it.

  • Top comments (2)

    Collapse
     
    brense profile image
    Rense Bakker

    Its not so much performance thats the issue with using the array index as a key. The problem is that when you remove an item from the array, the same index doesnt point to the same item anymore, which leads to wonky UI behavior (the wrong item disappearing from the interface). If you are not removing items from the array or otherwise change the order of the items in the array, there is no problem with using the array index as key.

    Collapse
     
    ifourtechnolab profile image
    Harshal Suthar

    Maybe I agree with this. Thank you so much for sharing your thoughts.