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.