Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why TextInput's `.clear()` doesn't trigger `onChangeText` callback?

I am programmatically clearing the TextInput’s value via .clear() method.
I also subscribed my state to onChangeText but on .clear() invocation, my state doesn’t change.

Why .clear() doesn’t trigger onChangeText? Isn’t it changing the text value?

Example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function MyComponent() {
  const [value, setValue] = useState("");
  const ref = useRef();

  const handlePress = () => {
    ref.current.clear();
  };

  return (
    <View>
      <TextInput onChangeText={setValue} ref={ref} />;
      <Button
        title="clear"
        onPress={handlePress} // <<< when this is called, onChangeText doesn't called?
      />
    </View>
  );
}

>Solution :

In general across multiple different APIs and event systems, when you change the value of a field/control via code, it doesn’t trigger any event handlers related to that change. (There are APIs/systems that are exception to that general rule, but they’re rare.) The event handlers are there for when the change is done via the user operating on the field/control in the UI. For example, with a DOM input element, setting the value property changes the value, but doesn’t trigger any events (such as change or input); submitting a form via its submit function doesn’t trigger a submit event. React Native is just following the same pattern in their fields/controls.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading