React Native. How do I keep focus to a text input when the page re-renders on timer tick

3.6k views Asked by At

I'm writing a timer app using react native on android in clojurescript (using reagent hopefully not important).

I have a TextInput where I accept text from the user to name the timers. Whenever my timer ticks, the entire android application re-renders and I lose focus on the TextInput. I am currently using onChangeText to save the characters I am typing, is there a way to keep focus on the text input while the timer is ticking?.

Thanks.

1

There are 1 answers

1
John Shammas On BEST ANSWER

The simplest solution is to call this.refs.yourTextInput.focus() inside of the componentDidUpdate method. However, this will likely cause the keyboard to animate down, and then animate up again.

The root of the problem is that your timer value and your TextInput share the same scope, so when the state is updated, both the timer and TextInput are re-rendered via the render function. Ideally, you can:

Put your timer text in a custom component, and add a method on that custom component to set its own state. This will cause only the custom component to re-render as long as the custom component's state is the one which is updating.