Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React looping over Map vs Array

I’ve got an issue where I am trying to loop over a map and return a <p> element in each case. It isn’t working as I believe it should, however it is working for an array.

The code is as follows:

  <div className="previousRounds">
    {myTestMap.forEach(() => (
      <p>I've looped over a map to print this</p> //This doesn't work
    ))}

    {currentUsersPicks.map(() => (
      <p>I've looped over an array to print this</p> //This works
    ))}

  </div>

The map definitely exists and if I replace the <p></p> tags with console.log then I do get output printed to the console.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s a screenshot of the webpage.

So why does this work for an array and not a map?

Expecting this to work whether it’s a map or array

>Solution :

The map() method returns a new array, whereas the forEach() method does not return a new array. The map() method is used to transform the elements of an array, whereas the forEach() method is used to loop through the elements of an array.


For Each

The following two code examples produce exactly the same result, you can think of forEach like the first more traditional for loop.

const myArr = ["my", "array", "test"];

for (const word of myArr) console.log(word);

myArr.forEach((word) => console.log(word));
Map

The following two code examples also produce exactly the same result, you can think of map like the first more traditional approach on mapping.

const myArr = ["my", "array", "test"];

const newArr1 = [];
for (const word of myArr) newArr.push(`${word}-1`);

const newArr2 = myArr.map((word) => `${word}-1`);

So when you want to render items in react you need to use the map method on the array to return a new array containing your JSX. Here is an example:

const MyComponent = () => {
  const names = ["John", "Sarah", "Mike"];
  return (
    <ul>
      {names.map((name) => {
        return <li key={name}>{name}</li>;
      })}
    </ul>
  );
};

You should always provide a key to your repeated JSX item, you can learn more about keys and why react uses them here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading