Search code examples
arraysreactjsobjectfor-loopecmascript-next

Not iterating over my entire array from my for()


I am writing an app in React, meanwhile I was playing with some of the new ECMA 17 features trying to get a little more familiar. Originaly in a parent Component I used Map() to itterate a new div for every index in my array.

For a new component though a child of the Map one, I thought I would use the Object.enteries() using the for (){} format instead of Map. I thought I could simply return the values that way however it only partially is working.

The problem I am getting is it will only iterate over the first index of my array. It only console logs and returns the div of the first index in the array. I am completely lost as to why this is only partially working.

import React from 'react';

const InnerCard = (props) => {
    // const myInnerOptions = 
    const myInnerOptions = props.cardSelected  
    for (let [key, value] of Object.entries(myInnerOptions)) {
        console.log(`key: ${key} Card Value: ${value} this is from 
          InnerCards.js`);
        return (
            <div key={key}>inside innerCard: {value}</div>
        )
     }  /*  NOTE  at this point I am having a problem. 
          // thos will only print 1 div   it will only  push the first key  
          //   div out  not the second.  props should be pushing an array of 
               2 items up.  */

     console.log(props.cardSelected, 'here here');
         //for (let [key, value] of Object.entries())

     return (
         <div>{myInnerOptions}</div>

     );
 }

 export default InnerCard; 

it consoles at the end only the first index and value of the array. I did notice though the very first console log is...
[] "here here"
which means inbetween my const and before the return () that console.log is acting first before any of the parent components. Is my problem that I need to use a componentWillMount() at this point? Obviously it still works as when I click on a div it is passing the first index in, so I am thinking asynchronism isnt at play here.. but I am still so green horn that... Ive come to a stand still here tryignt of igure out ...

why am I only going over the first index of the array only and not the 2nd? Is it my for()? (maybe this isn't enough of my code to help.. insufecient data for a meaningful answer) (sorry long winded..)


Solution

  • The problem with your code is when the for reach the first return, is not going to continuing painting the other divs.

    Basically, when you call return, the render function is going to finalize there. The difference with a map is that it returns the child when they have mapped.

    What you are doing is basically this:

    if (true) {
      return 'Something';
    }
    
    // Any coding at this point is not going to be executed.
    

    The same applies to the for cycle.