0

sorry for my English language

I wrote a function for push JSX elemnts in an array and return that:

import * as React from 'react';
import { View, Text } from 'react-native';
import { Button} from 'react-native-paper';

const buttonLoop = () => {
    const items = []
    for (var i = 1; i <= 2; i++) {
        items.push(<Button icon="camera" onPress={() => alert(i/* Problem is here*/)}>Loop {i/* It work true*/}</Button>)
    }

    return items;
}

as you can see i inside of element work truly, and show 1 for Button1 and show 2 for Button2. But when i click on button it show "3" for both button, I want show "1" for Button1 and "2" for Button2

in JQuery i had't this problem, why it don't work true and what's solution?

mojtaba sh
  • 93
  • 7

1 Answers1

0

Think of it like this, When you click the button the i you are referring to is pointing to the one in the loop which has the value 3 so the way to fix this is passing the i as a parameter like below

This happens when using var due to closures, you will have to use the let keyword.

const ButtonLoop = () => {
  const items = [];
  for (let i = 1; i <= 2; i++) {

    items.push(
      <Button icon="camera" onPress={() => alert(i)} title={i}>
        Loop {i}
      </Button>
    );
  }

  return items;
};
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50