When we have an input field on the bottom of the screen and we focus it, the keyboard covers the field and we will not know what we are typing inside.

My solution is a mix of two StackOverflow answers, which I will reference at the bottom. Also, apparently the React Native team tackled this issue in the 0.30.0 release. I tried it and it didn’t work the way I wanted, but maybe it was me doing something wrong.

Oh and of course this might not be the best way to do it at all, but it works for me and doesn’t look awful.

1. We import a couple of additional things.

import { WhateverYouImport, Dimensions, findNodeHandle } from 'react-native'
var RCTUIManager = require('NativeModules').UIManager

2. We copy/paste these two methods into the component.

onInputFocus(refName) {
  setTimeout(() => {
    let scrollResponder = this.refs.scrollView.getScrollResponder()
    scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
      findNodeHandle(this.refs[refName]),
      20, // additionalOffset
      true
    )
  }, 100)
}

resetWindowHeight() {
  let scrollView = this.refs.scrollView
  let screenHeight = Dimensions.get('window').height
  setTimeout(() => {
    RCTUIManager.measure(scrollView.getInnerViewNode(), (...data) => { 
      // data[3] is the height of the ScrollView component with content.
      scrollView.scrollTo({ y: data[3] - screenHeight, animated: true })
    })
  }, 100)
}

3. We update the render method with appropriate ref, onFocus and onBlur props where needed.

<ScrollView style={styles.scrollView} keyboardDismissMode="on-drag" ref="scrollView">
  <TextInput ref="someTextInput" onFocus={this.onInputFocus.bind(this, 'someTextInput')} onBlur={this.resetWindowHeight.bind(this)} style={styles.inputField} value="Some Value" />
</ScrollView>

References:

http://stackoverflow.com/questions/33049731/scroll-to-bottom-of-scrollview-in-react-native
http://stackoverflow.com/questions/29313244/how-to-auto-slide-the-window-out-from-behind-keyboard-when-textinput-has-focus
https://github.com/facebook/react-native/commit/8b78846a9501ef9c5ce9d1e18ee104bfae76af2e

Leave a Reply

Your email address will not be published. Required fields are marked *