Skip to content

Instantly share code, notes, and snippets.

@ChronSyn
Created April 19, 2020 14:46
Show Gist options
  • Save ChronSyn/88f1459e44420b617370b6d1de6c3c2d to your computer and use it in GitHub Desktop.
Save ChronSyn/88f1459e44420b617370b6d1de6c3c2d to your computer and use it in GitHub Desktop.
React + React Native useKeyboard hook
import { useEffect, useState } from "react";
import { Keyboard, KeyboardEvent } from "react-native";
export const useKeyboard = (): [number, boolean] => {
const [keyboardHeight, setKeyboardHeight] = useState(0);
const [keyboardVisible, setKeyboardVisible] = useState(false);
function onKeyboardDidShow(e: KeyboardEvent): void {
setKeyboardHeight(e.endCoordinates.height);
setKeyboardVisible(true);
}
function onKeyboardDidHide(): void {
setKeyboardHeight(0);
setKeyboardVisible(false);
}
useEffect(() => {
Keyboard.addListener("keyboardDidShow", onKeyboardDidShow);
Keyboard.addListener("keyboardDidHide", onKeyboardDidHide);
return (): void => {
Keyboard.removeListener("keyboardDidShow", onKeyboardDidShow);
Keyboard.removeListener("keyboardDidHide", onKeyboardDidHide);
};
}, []);
return [keyboardHeight, keyboardVisible];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment