0

I have component in React-Native:

 <View style={{ flexDirection: "column", justifyContent: "space-around", width: "100%", marginTop: 30 }}>
      <MeasurementValues />
 </View>

with function :

const list =  [{"name": "field1"}, {"name": "field2"}, {"name": "field3"}];

const changeValue = (field, text) => {
        console.log(field + " => " + text);
    };

const MeasurementValues = () => {
        var values = [];
       for (var key in list) {
            values.push(<TextInput placeholder={list[key].name} keyboardType="numeric" onChangeText={(text) => changeValue(list[key].name.toString(), text)} />)
        }
        return <>{values}</>
    }

and when I enter something in all fields, I always get "field3" as field variable in console.log.

placeholder is ok. Has field1,field2 and field3 value. Only onChangeText get field3 as value.

What I'm doing wrong? Thank you

Mateusz
  • 1
  • 1
  • 1
    Side note: That's not a good way to loop through an array, see why and what your various options are [here](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476). – T.J. Crowder Oct 01 '20 at 10:27
  • Separately from the above, when you're converting every entry in an array to something else, the idiomatic way to do that is `map`, which coincidentally would fix the closures-in-loops problem that you have in that code: `const values = list.map(({name}) => changeValue(name, text)} />);`. – T.J. Crowder Oct 01 '20 at 10:30
  • Thank you! it's working. Notice about loops I read. – Mateusz Oct 01 '20 at 10:45

0 Answers0