Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 201
GTDev Avatar asked Dec 09 '15 08:12

GTDev


People also ask

How do you focus on text input in react native?

When the TextInput is in focus the keyboard appears automatically and this prompts the user to type in. You can use autoFocus prop to make the textInput on focus in react native. When the autoFocus is made true the input get focused on componentDidMount lifecycle. The default value of autoFocus is false.

Why does the input field lose focus after typing a character react?

it is because you are rendering the form in a function inside render(). Every time your state/prop change, the function returns a new form. it caused you to lose focus.

How do you select the next TextInput after pressing the Next keyboard button?

To select the next TextInput after pressing the "next" keyboard button with React Native, we can assign refs to the TextInput s we want to set focus on. And then we call focus on the ref. current of the TextInput to set focus on the input.

What is onBlur react native?

What is onBlur event in React. React onBlur behaves just like the native JavaScript version of blur. Every time you get out of focus from the input field, the event will trigger. It doesn't matter if the value has changed or not, every time you get out of focus.


1 Answers

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.

like image 123
John Shammas Avatar answered Sep 23 '22 14:09

John Shammas