Handling lack of form reactivity when opening the Keyboard on React Native
When you focus a TextInput
in React Native the OS will show the virtual keyboard while scrolling the focused input above the keyboard. While this feature is awesome, this not always works. First you'll need to wrap your form inside a ScrollView
and hope it will do the trick (this will mostly work) — the problem is if your form is inside a modal / absolute positioned wrapper, it may not work properly. The virtual keyboard will open on top on your form and your user will be 'what am I typing lol'. Since you're using a ScrollView
wrapper the user might be able to scroll up until the input shows up, but most of the time the time the wrapper won't have enough space to show the input if the target input is at the end of the form.
One way to solve this issue is by using the Keyboard events keyboardDidShow
and keyboardDidHide
to capture the keyboard dimensions:
const YourComponent = () => {
const [keyboardHeight, setKeyboardHeight] = useState(0)
const onKeyboardDidShow = ({endCoordinates}) => {
setKeyboardHeight(endCoordinates.height)
}
useEffect(() => {
const didShowEvent = Keyboard.addListener("keyboardDidShow", onKeyboardDidShow );
return () => {
// cleanup
didShowEvent.remove()
}
}, [])
The keyboardDidShow
event will return the virtual keyboard dimensions in endCoordinates
property. Use these coordinates to improve your application reactivity when the keyboard is open (in the example we capture the height
property). If you're using a modal, for example, you can limit the modal to end where the keyboard starts (make sure to use a ScrollView
inside this modal so the content won't get cropped).