Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save intergalacticspacehighway/f60aaaf773d1c955c53e27a2ad099bd5 to your computer and use it in GitHub Desktop.
Save intergalacticspacehighway/f60aaaf773d1c955c53e27a2ad099bd5 to your computer and use it in GitHub Desktop.
Hook to get keyboard height in React Native and add bottom/padding inset on a view.
import { Keyboard, Platform, KeyboardEvent } from 'react-native';
const useKeyboardBottomInset = () => {
const [bottom, setBottom] = React.useState(0);
const subscriptions = React.useRef([]);
React.useEffect(() => {
function onKeyboardChange(e) {
if (
e.startCoordinates &&
e.endCoordinates.screenY < e.startCoordinates.screenY
)
setBottom(e.endCoordinates.height);
else setBottom(0);
}
if (Platform.OS === 'ios') {
subscriptions.current = [
Keyboard.addListener('keyboardWillChangeFrame', onKeyboardChange),
];
} else {
subscriptions.current = [
Keyboard.addListener('keyboardDidHide', onKeyboardChange),
Keyboard.addListener('keyboardDidShow', onKeyboardChange),
];
}
return () => {
subscriptions.current.forEach((subscription) => {
subscription.remove();
});
};
}, [setBottom, subscriptions]);
return bottom;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment