Force focus ReactNative TextInput
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
Related videos on Youtube
Ruben Hamakers
Updated on June 04, 2022Comments
-
Ruben Hamakers almost 2 years
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 afteronBlur()
?Cheers.
-
Ruben Hamakers over 5 yearsHmm I'm getting a ref is not defined error, I literally copied the code from your snack?
-
Marcel Kalveram over 5 years@RubenHamakers Sorry to hear that you're having issues. I just ran it on Android and iOS and it worked fine for me. Can you try again and paste the complete error message in here?