I want to be able to focus the TextInput after it has mounted and I’ve had a couple of solutions for this but sadly none of them works
- autoFocus prop: causes navigation issues
- using ref to focus
<ScreenWrapper
onEntryTransitionEnd={() => inputRef.focus()}
>
<TextInput
ref={(el) => inputRef.current = el}
>
This doesn’t focus the TextInput if I reload the page. I believe by the time focus is called, TextInput hasn’t mounted
- ref plus useEffect
Basically the same as above but I added a hook to run on change in ref.current
useEffect(() => {
if(inputRef.current) inputRef.current.focus();
}, [inputRef.current])
This worked perfectly but react recommends against the use of refs as dependents
How can I achieve this efficiently?
I also tried setting a state when I set the ref value in TextInput. And then using an effect hook on that state, but it shows similar results as autoFocus, causing navigation transition issues
2
Answers
You simply don’t need any dependencies to just focus the input when the component is mounted. Also, passing a function as the ref is redundant when passing the ref returned by
useRef
has the exact same effect.Can you call focus on it as soon as it loads by using a callback ref
e.g.