Nicolas Meienberger Nicolas Meienberger - 1 month ago 9
React JSX Question

Rendering a dynamic ListView and passing key to method

I'm trying to render a ListView with a dynamic amount of switches so in my _renderRow function I did the following : (list contains a key, value array)

_renderRow(list) {
var jsxList = [];

for (var k in list) {
jsxList.push(
<View>
<Text>{list[k]}</Text>
<Switch value={this.state.switches[k]} onValueChange={() => this._changeValue(k)}/>
</View>
)
}

return (
<View>
{jsxList}
</View>
)
}


My problem is that when I trigger the switch, the key sent to _changeValue is always the last of my list even though when I pushed it to my array it wasn't.

Answer

In JavaScript, variables declared using var gets hoisted, so when _changeValue(k) runs, k will always be the last value it was assigned to. You can solve this using a closure:

for (var k in list) {
  (function () {
    jsxList.push(
      <View>
        <Text>{list[k]}</Text>
        <Switch value={this.state.switches[k]} onValueChange={() => this._changeValue(k)}/>
      </View>
    )
  }())
}

Or, if you use ES6, you can use let to create a block scoped variable:

for (let k in list) {
  jsxList.push(
    <View>
      <Text>{list[k]}</Text>
      <Switch value={this.state.switches[k]} onValueChange={() => this._changeValue(k)}/>
    </View>
  )
}
Comments