Reputation: 33
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.
Upvotes: 1
Views: 1817
Reputation: 54
onChangeText returns the string of that TextInput
onChangeText# Callback that is called when the text input's text changes. Changed text is passed as a single string argument to the callback handler.
That means that you dont need to use event.target.value (that is valid for the onChange callback) So try:
function handleChange(i, event) {
console.log(i)
const values = [...fields];
values[i].value = event;
setFields(values);
}
Upvotes: 1