Vipul Sanjay
Vipul Sanjay

Reputation: 33

react native adding textinput on button click?

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

Answers (1)

iGionea
iGionea

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

Related Questions