Search code examples
react-nativereact-native-iosreact-native-textinput

Force focus ReactNative TextInput


I'm having trouble force focussing a react native TextInput field. It's focused when the page loads with autofocus={true}.

But after blurring I would need to press the text input field, but that's hidden because of design reasons. Is there a way to document.getElementById("myText").focus(); in react native that I can call after onBlur()?

Cheers.


Solution

  • You need to assign the TextInput field to a ref like this: <TextInput ref={ref => (this.ref = ref)} />

    Then you can programmatically focus it by running focus() on it, like so: this.ref.focus();

    Here's a little Snack where I run the focus/blur function when pressing a button: https://snack.expo.io/@marcelkalveram/auto-focus-input-field-using-ref

    It should be easy to replicate this for your navigation scenario.

    In case you're using react-navigation, this is the part of the docs you'll be interested in: https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle