im trying to add a textinput field if user clicks a button, i was able to add a textinput field code but i cannot retrieve the onChangeText value. its outputs an empty array. im new to react .help :)
function AddField({ navigation }) {
const [fields, setFields] = useState([{ value: null }]);
function handleChange(i, event) {
console.log(i)
const values = [...fields];
values[i].value = event.target.value;
setFields(values);
}
function handleAdd() {
const values = [...fields];
values.push({ value: null });
setFields(values);
}
function handleRemove(i) {
const values = [...fields];
values.splice(i, 1);
setFields(values);
}
return (
<View>
<Button title="add" onPress={() => handleAdd()} />
{fields.map((field, idx) => {
return (
<View key={`${field}-${idx}`}>
<TextInput
type="text"
placeholder="Enter text"
value={field.value}
onChangeText={(text) => handleChange(idx, text)}
/>
<Button title="sub" onPress={() => handleRemove(idx)} />
</View>
);
})}
</View>
);
}
thank you.
its outputs an empty arraywhere exactly? You havevalue={field.value}so if you can type into the fields and see the text, the code should work fine. I checked the state logic and it seems to be OK: codesandbox.io/s/upbeat-nightingale-098lx?file=/src/App.jshandleChange(idx, text)vshandleChange(i, event)