1

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.

2
  • 2
    its outputs an empty array where exactly? You have value={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.js Commented Apr 29, 2021 at 10:29
  • 2
    As per the answer, I inadvertently fixed your code :) handleChange(idx, text) vs handleChange(i, event) Commented Apr 29, 2021 at 10:42

1 Answer 1

1

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);
    
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.