0

I'm trying to create a group of react elements through a for loop. However, it seems that, rather than each element getting its own copy of the variables per for loop, they are tied to whatever the variable is at the end of the for loop (where i = 3). How can I prevent this. Thanks.

makeCheckboxes() {
    var checkboxes = [];
    for(var i = 0; i < this.props.flagNames.length; i++) {
        console.log("Making checkbox. i = " + i);
        checkboxes.push((
            <React.Fragment>
                <label><input type="checkbox" name="reportFlags" value="fraud" checked={this.state.reportFlags[i]} onClick={() => this.handleCheck(i)}/>{this.props.flagNames[i]} </label><br />
            </React.Fragment>
        ));
    }
    return checkboxes;
};
metalhead696
  • 195
  • 2
  • 11
  • 1
    Use 'let' instead of 'var'. 'Let' is block-scope. see here https://stackoverflow.com/questions/34750447/let-keyword-and-closures – proti Sep 04 '18 at 20:14

1 Answers1

1

just replace

for(var i = 0; i < this.props.flagNames.length; i++) {

by

for(let i = 0; i < this.props.flagNames.length; i++) {

actually it will create a closure, so it should sove the problem

if you still want to use var you can change your code like this using immediately-invoked function expression iife

for(var i = 0; i < this.props.flagNames.length; i++) {
    console.log("Making checkbox. i = " + i);
    checkboxes.push((
        <React.Fragment>
            <label>
               <input 
                  type="checkbox" 
                  name="reportFlags" 
                  value="fraud" 
                  checked={this.state.reportFlags[i]} 
                  onClick={((j) => () => this.handleCheck(j))(i)} //here is the iife
               />
               {this.props.flagNames[i]} 
            </label><br />
        </React.Fragment>
    ));
}
return checkboxes;
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56