Force focus ReactNative TextInput

12,724

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

Share:
12,724

Related videos on Youtube

Ruben Hamakers
Author by

Ruben Hamakers

Updated on June 04, 2022

Comments

  • Ruben Hamakers
    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 after onBlur()?

    Cheers.

  • Ruben Hamakers
    Ruben Hamakers over 5 years
    Hmm I'm getting a ref is not defined error, I literally copied the code from your snack?
  • Marcel Kalveram
    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?