skip to Main Content

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.

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

2

Answers


  1. forEach returns undefined which produces no JSX. Your map actually returns some JSX so that’s why it renders.

    If you change your callback in map to not use a return it will not render anything either:

    array.map(() => {
       <p>I've looped over an array to print this</p>
    })
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search