2

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.

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm I'm getting a ref is not defined error, I literally copied the code from your snack?
@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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.