I've seen this hack for native apps to auto scroll the window, but wondering best way to do it in React Native... When a <TextInput>
field gets focus and is positioned low in the view, the keyboard will cover up the text field.
You can see this issue in example UIExplorer's TextInputExample.js
view.
Does anyone have a good solution?
You can use ScrollView to control screen up and down movements. As long as user hasn't focused any TextInput , you can disable scroll. On focus, just shift up the scrollview using Content Offset prop.
KeyboardAvoidingView is a React Native built-in component with full JS implementation. It relies on RN's keyboard events ( keyboardWillChangeFrame on iOS & keyboardDidHide/Show on Android) and, based on provided behavior prop, applies additional padding, translation, or changes container's height.
Making the text input to scroll in react native, you have to add numberOflines to it, this is the property which takes the value as int, how much lines you want to display in text input you have to provide the number and after that, the text input will get scroll property automatically.
2017 Answer
The KeyboardAvoidingView
is probably the best way to go now. Check out the docs here. It is really simple compared to Keyboard
module which gives Developer more control to perform animations. Spencer Carli demonstrated all the possible ways on his medium blog.
2015 Answer
The correct way to do this in react-native
does not require external libraries, takes advantage of native code, and includes animations.
First define a function that will handle the onFocus
event for each TextInput
(or any other component you would like to scroll to):
// Scroll a component into view. Just pass the component ref string. inputFocused (refName) { setTimeout(() => { let scrollResponder = this.refs.scrollView.getScrollResponder(); scrollResponder.scrollResponderScrollNativeHandleToKeyboard( React.findNodeHandle(this.refs[refName]), 110, //additionalOffset true ); }, 50); }
Then, in your render function:
render () { return ( <ScrollView ref='scrollView'> <TextInput ref='username' onFocus={this.inputFocused.bind(this, 'username')} </ScrollView> ) }
This uses the RCTDeviceEventEmitter
for keyboard events and sizing, measures the position of the component using RCTUIManager.measureLayout
, and calculates the exact scroll movement required in scrollResponderInputMeasureAndScrollToKeyboard
.
You may want to play around with the additionalOffset
parameter, to fit the needs of your specific UI design.
Facebook open sourced KeyboardAvoidingView
in react native 0.29 to solve this problem. Documentation and usage example can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With