Bulaxy
Bulaxy

Reputation: 119

render buttons inside component onPress function show last i. React-Native

I am trying to load a component containing array from redux (in example case, test). I am able to create the buttons and have the right title, however, the onPress function is not displaying the correct value

//expected outcome when press button "a"
0
//Outcome
2
class Test extends React.Component {
    render() {
        var buttons = []
        for (var i = 0; i < this.props.test.length; i++) { // this.props.test = ["a","b"]
            buttons.push(
                <Button
                    title={this.props.test[i]}
                    onPress={() => console.log(i)}
                />
            )
        }
        return (
            <View>
                {buttons}
            </View>
        );
    }
}

Upvotes: 2

Views: 206

Answers (1)

akhtarvahid
akhtarvahid

Reputation: 9779

You need to define let instead of var

for (let i = 0; i < this.props.test.length; i++) { // this.props.test = ["a","b"]
            buttons.push(
                <Button
                    title={this.props.test[i]}
                    onPress={() => console.log(i)}
                />
            )
        }

The main difference between var and let is that instead of being function scoped, let is block scoped. What that means is that a variable created with the let keyword is available inside the “block” that it was created in as well as any nested blocks. When I say “block”, I mean anything surrounded by a curly brace {} like in a for loop or an if statement.

for better understanding of scope. visit to https://tylermcginnis.com/var-let-const/

Try to use map() function

export default class Test extends React.Component {
  state={value:0}
  handleClick=id=>{
    this.setState({value:id})
  }
    render() { 
        let buttons;
        buttons = this.props.test.map(te=>
        <Button
            key={te}
            title={te}
            onPress={() => this.handleClick(te)}
          />
        )
        return (
            <View>
                {buttons}
                <Text>{this.state.value}</Text>
            </View>
        );
    }
}

Upvotes: 2

Related Questions