ReactJs: How to turn a map loop into a for loop?

Asked
Active3 hr before
Viewed126 times

9 Answers

reactjs
90%

Thanks for contributing an answer to Stack Overflow!, How many iterations to reach the sequence? ,Join Stack Overflow to learn, share knowledge, and build your career., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

const number = [1, 2, 3, 4];

//using map example
const square_map = number.map(num => num * num);
console.log('using map', square_map);

//using forEach example
const square_Foreach = [];
number.forEach(num => square_Foreach.push(num * num));
console.log('using forEach', square_Foreach);

//using for example
const square_for = [];
const number_length = number.length;
for (let i = 0; i < number_length; i++) {
   square_for.push(number[i] * number[i])
};
console.log('using for loop', square_for);
88%

Wondering how to create loops in React? Learn about JSX and how to use methods like the map function to loop inside React JSX and render a list of items.,As you can see there are quite a few different ways in which you can render a list of items in React. I hope that after reading this article you are now more confident with React and know how to use loops in JSX.,When I first started with React, I realized quite early that I did not know how to loop through an array and render a list of items. The most common way of doing that is with the map function that will return JSX. You will rarely need a loop other than this one. Below you can see how it works.,99.99% of the time, I use the map function to render a list of items and, to be honest, I can’t recall any scenario in which I needed another loop. Nevertheless, you are not bound to it and can use any loop to render a list. All of these work fine:

If you have worked with React before, then there is a high probability that you know what JSX is, or have at least heard of it. JSX is a custom syntax extension to JavaScript which is used for creating markup with React. It might remind you a bit of a templating language, but with JSX you can use the full power of JavaScript. However, remember that JSX will not work directly in browsers and requires a build step to convert JSX markup into React.createElement function calls.

// JSX example

return (
  <div>
    <button onClick={onClickHandler}>Submit</button>
  </div>
)

// The above will be converted to something like this

return React.createElement(
    "div",
    {},
    React.createElement(
      "button",
      {
        onClick: e => {}
      },
      "Submit"
    )
  );
load more v
72%

function NameList() {
	const names = ['Bruce', 'Clark', 'Diana']
    return (
    	<div>
      {names.map(name => <h2>{name}</h2>)}
      	</div>
    )
}
load more v
65%

One of the best things about React is that doesn’t require you to learn a myriad of new methods to manipulate & render data. Instead, it relies heavily on the Javascript language itself for these common tasks. Remember that React will evaluate any Javascript expression you provide it, and this also includes arrays (it renders each array entry, starting at index 0). For those of you who are Javascript experts, you’ll know that we can use Javascript’s map method to quickly iterate over our array and create a new one with our desired values!,Easy enough! But what if our names were in an array, and couldn’t be hard coded into the component? In other words, how could we iterate over [‘Jake’, ‘Jon’, ‘Thruster’] and create LI’s for each of them?,And that’s it, you’ve mastered the art of iterating & rendering loops in React! If you’re interested in learning more, this post from Jason Lee is fantastic and worth a read.,Not so fast though — also remember that <li>Jake</li> actually boils down to React.createElement('li', null, ‘Jake’), so our elements are actually just methods that will be executed. What this means is that we need to convert our array from [‘Jake’, ‘Jon’, ‘Thruster’] to

var Hello = React.createClass({
    render: function() {
        return (
            <ul>
                <li>Jake</li>
                <li>Jon</li>
                <li>Thruster</li>
            </ul>
        )
    }
});
load more v
75%

This method, compared to the for-loops and map method, is the slowest one and doesn’t return the values like a map, so you need to have a special case to use it.,To do that, we can use few methods, one of the most popular is the map method, but we will cover the map in the separate section, and now we should focus on the other methods like loops or forEach method.,That method is useful when we use separate functions to render part of components, and it’s the best method for performance.,The second method that I’ve included in the example is the method with array.forEach().

// First one with For of loop
function renderComponent() {
  const products = ['orange', 'apple', 'watermelon'];

  const list = []

  for (const [i, product] of products.entries()) {
    list.push(<li>{product}</li>)
  }

  return (
    <div>
      {list}
    </div>
  )
}

function Parent(props) {
  return renderProducts();
}

// Second with forEach method
function renderComponent() {
  const products = ['orange', 'apple', 'watermelon'];

  const list = []

  products.forEach((product) => {
    list.push(<li>{product}</li>)
  })

  return (
    <div>
      {list}
    </div>
  )
}

function Parent(props) {
  return renderProducts();
}
load more v
40%

Introduced in ES6, the Map array function is by far my most used method of iterating over an array in React. ,Out of the three iterators above, our best option to iterate over an array in React inside of JSX is the Map function.,Why is it my most commonly used method of looping through arrays in React? Because it’s incredibly versatile, succinct, and easy to read once you wrap your head around it.,As with most things in web development, there are multiple ways to loop, or iterate, through an array in React using JavaScript.

const names = ['James', 'Paul', 'John', 'George', 'Ringo'];

function App() {
  return (
    <div>
      {names.map(name => (
        <li>
          {name}
        </li>
      ))}
    </div>
  );
}
load more v
22%

This guide demonstrates how to implement loops in common use cases, such as rendering a list of static data and outputting data from an API. ,Thus you can push your data along with its supporting HTML inside an array and then output that array inside your component's return statements enclosed in curly braces. There are several JavaScript loops that you can use for this purpose. Since map() is the most popular and easiest one, this guide extensively uses it in the examples. ,Consider a simple use case where you have to render a list of items on the DOM. ,Further, you can clean up your JSX by pushing the entire HTML in an array:

1return(
2	<>
3	{data}
4	</>
5)
load more v
60%

The map() method creates a new array with the result of calling a function for every array element.,The forEach method executes a provided function once for each array element.,I have used the arrow function for a shorter version of my code you can also use the normal javascript function. Both will give the same result.,Creates an array of values by running each element in collection thru iteratee. The iteratee is invoked with three arguments:(value, index|key, collection).

Syntax

array.map(function(currentValue, index, arr), thisValue)
load more v
48%

First, let’s review how you transform lists in JavaScript.,Below, we loop through the numbers array using the JavaScript map() function. We return a <li> element for each item. Finally, we assign the resulting array of elements to listItems:,Given the code below, we use the map() function to take an array of numbers and double their values. We assign the new array returned by map() to the variable doubled and log it:,Let’s assign a key to our list items inside numbers.map() and fix the missing key issue.

load more v

Other "reactjs-undefined" queries related to "ReactJs: How to turn a map loop into a for loop?"