2

I have a button, that is part of an array in jsx.

The button displays the index, 1, 2, 3, etc. When I press the button however and console log it I get the same value each time, the length of the for loop. I cannot wrap my head around it. I was thinking of maybe having the wrong keys and coupling two components, but that's not the problem.

 const getRows = () => {
    var rows = [];
    for (var i = 0; i < Math.max(dropped2 && dropped2.length, dropped1 && dropped1.length); i++) {
      console.log(i);
      rows.push(
        <div key={i}>
          <Browser>
            <DropItArranged left dropped={dropped2 && dropped2.length > i && dropped2[i]} index={i} selected={displayIndex === i} />
            <DropItArranged dropped={dropped1 && dropped1.length > i && dropped1[i]} index={i} selected={displayIndex === i} />
            <button key={"selectButton" + i} className={displayIndex === i ? "button is-link" : "button"} onClick={e => { console.log(i); dispatch(allActions.changeDisplayedContent(i)) }} > {i}</button>
          </Browser>
        </div>
      );
    }
    return rows;
  }

Output is always the length of the for loop.

Here is a clean version:

    var rows = [];
    for (var i = 0; i < Math.max(dropped2 && dropped2.length, dropped1 && dropped1.length); i++) {
      rows.push(
        <div key={i}>
             <button key={"selectButton" + i} onClick={e => { console.log(i); } > {i} </button>
        </div>
      );
    }
    return rows;
  

This is the return function:

return (
    <LeftPanel>
      <div>
        <h5 className="title is-5">Browse</h5>
      </div>
      <Column>
        {getRows()}
      </Column>
    </LeftPanel>
  )
semyd
  • 430
  • 4
  • 17

1 Answers1

1

You can try to change var i = 0 into let i = 0. Your issue relate to the Scope variable in Javascript. The main difference between let and var is that scope of a variable defined with let is limited to the block in which it is declared while variable declared with var has the global scope.

For this case, when you use let instead, there is a new variable i created for each invocation of the loop that is scoped just to the block of the loop. So, you can have new variable for each console.log. Following this one for more detail: JavaScript: Understanding let scope inside for loop

Nguyen Vu Quang
  • 831
  • 6
  • 5
  • The issue about let and var only happens when they are handled in an async way. Here I don't think it is a problem. – Eric Oct 29 '20 at 16:22
  • I dont think so. `let` and `var` has different scope so the issue can happen in each code line, not just async way. – Nguyen Vu Quang Oct 29 '20 at 16:27
  • Thank you this worked perfectly. I always write it with let, so I have not encountered this error before (I copied a part of the code). I appreciate your and other's input! – semyd Oct 29 '20 at 16:37