Automatically scroll the view up when keyboard is shown in react-native

Varun Gupta picture Varun Gupta · May 27, 2016 · Viewed 10.8k times · Source

How can I automatically scroll the view up when I focus in a TextInput box and a keyboard is shown such that the TextInput box is not hidden behind the keyboard? This question has been asked on StackOverflow a few times and I implemented the solution here which is the general solution advised in most of the answers. This solution works fine in the iPhone simulator but doesn't work on the actual phone. Has anyone else experienced this problem that the solution doesn't work on the actual phone?

Second thing that I noticed after adding this solution is that now if I am focussing in a TextInput box and keyboard is shown, if I press a button or try to focus into a different TextInput box, the first touch is always consumed to hide the keyboard and the button is not pressed or the other TextInput box is not focussed. It is a little annoying for the user to have to do the operation twice. Has anyone else observed this problem?

Please let me know if you have any inputs on how to solve these problems?

Answer

Daniel Basedow picture Daniel Basedow · May 28, 2016

I assume you are using this solution. I ran into the same problem and made some adjustments (see gist). I addressed both problems you describe. keyboardShouldPersistTaps solves your second problem.

I have not found the exact reason why the spacing works in Simulator but not on a real device. It has something to do with the timing. The original code sets a timeout on input focus and tries to scroll down after 50ms. Increasing this to for example 500ms makes it work on devices too, but I don't really like adding magic timeouts that I don't understand. I changed it, so onFocus I look up the element to scroll to and store a reference. When onKeyboardDidShow fires I use the reference.