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

1

6

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.

Turnkey answered 9/12, 2015 at 8:18 Comment(1)
Did you try View.requestFocus();? And I do not understand why "application re-renders" on each tick.Radiolocation
C
6

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.

Couch answered 12/12, 2015 at 23:18 Comment(1)
This may work (and I'm probably going to accept it for bounty) but it does require some stateful changes without a single state tree so it's not purely functional. I'm sort of wondering if there is a solution that adheres to github.com/staltz/flux-challenge. I'm hypothesizing react + flux like architectures have problems with user input + asynchronous updates.Turnkey

© 2022 - 2024 — McMap. All rights reserved.