How do I refocus a <TextInput> after an event?

Viewed 125

When the screen loads, I use the following code to focus on a :

useEffect(() => {
  InteractionManager.runAfterInteractions(() => {
    if (refText.current) {
      refText.current.focus();
    }
  });
}, []);

This works as expected. However, on a submit event, the needs focus again.

function myEvent() {
  if (refText.current) {
    refText.current.focus();
  }
}

This does not focus on the text again. Any ideas?

1 Answers

Actually, i don't know why you'd need a if statement inside your submit handler to set the focus on the TextInput, but anyways, I presume you have a event handler on your Button declaration. E.g:

function App() {
  const textRef = useRef();

  const handleSubmit = () => {
    if (textRef.current) textRef.current.focus();
  };

  return (
    <View>
      <TextInput placeholder="Input" ref={textRef}/>
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
}
});

It works fine as you can see in this Sandbox.

Related