Skip to content

Instantly share code, notes, and snippets.

@whisher
Created October 28, 2021 15:38
Show Gist options
  • Save whisher/8dc1f0f61e43e1f509d889b98cb7c146 to your computer and use it in GitHub Desktop.
Save whisher/8dc1f0f61e43e1f509d889b98cb7c146 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import { Keyboard, View, Dimensions, Platform, StyleSheet } from "react-native";
const styles = StyleSheet.create({
container: {
left: 0,
right: 0,
bottom: 0,
},
});
export const KeyboardSpacer = ({ style, onToggle = () => null }) => {
const [keyboardSpace, setKeyboardSpace] = useState(0);
useEffect(() => {
const updateKeyboardSpace = (event) => {
if (!event.endCoordinates) {
return;
}
const screenHeight = Dimensions.get("window").height;
const newKeyboardSpace = screenHeight - event.endCoordinates.screenY;
setKeyboardSpace(newKeyboardSpace);
onToggle(true, newKeyboardSpace);
};
const showEvt =
Platform.OS === "android" ? "keyboardDidShow" : "keyboardWillShow";
const showListener = Keyboard.addListener(showEvt, updateKeyboardSpace);
const resetKeyboardSpace = () => {
setKeyboardSpace(0);
onToggle(false, 0);
};
const hideEvt =
Platform.OS === "android" ? "keyboardDidHide" : "keyboardWillHide";
const hideListener = Keyboard.addListener(hideEvt, resetKeyboardSpace);
return () => {
showListener.remove();
hideListener.remove();
};
}, []);
return <View style={[styles.container, { height: keyboardSpace }, style]} />;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment