Skip to content

Instantly share code, notes, and snippets.

@chirag04
Created July 15, 2016 16:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chirag04/d7a7d58f4afc9520a51f511ce7f67788 to your computer and use it in GitHub Desktop.
Save chirag04/d7a7d58f4afc9520a51f511ce7f67788 to your computer and use it in GitHub Desktop.
import React from 'react';
import ReactNative from 'react-native';
const {
Keyboard,
TextInput,
ScrollView,
findNodeHandle,
} = ReactNative;
// tab height + listitem bottom padding + textinput height
const ADDITIONAL_OFFSET = 35 + 50;
class KeyboardAvoidingScrollView extends React.Component {
componentWillMount() {
this.subscriptions = [
Keyboard.addListener('keyboardDidShow', this.keyboardDidShow),
];
}
componentWillUnmount() {
this.subscriptions.forEach((sub) => sub.remove());
}
keyboardDidShow = () => {
const currentlyFocusedField = TextInput.State.currentlyFocusedField();
const scrollResponder = this.refs.keyboardAvoidingScrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
findNodeHandle(currentlyFocusedField),
ADDITIONAL_OFFSET,
true
);
};
render() {
const { children, ...props } = this.props;
return (
<ScrollView
{...props}
ref="keyboardAvoidingScrollView"
keyboardDismissMode="on-drag"
>
{children}
</ScrollView>
);
}
}
KeyboardAvoidingScrollView.propTypes = {
...ScrollView.propTypes,
};
export default KeyboardAvoidingScrollView;
@spidergears
Copy link

@chirag04 I tried using this component in my app. It seems to work fine most of the time, except a few time when the component leaves some whitespace at the bottom, even when keyboard is not visible.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment