Skip to content

Instantly share code, notes, and snippets.

@louicoder
Last active July 31, 2024 12:11
Show Gist options
  • Save louicoder/c33cc2a8e212073157cd6e68814c6107 to your computer and use it in GitHub Desktop.
Save louicoder/c33cc2a8e212073157cd6e68814c6107 to your computer and use it in GitHub Desktop.
React NAtive Hook for getting keyboard height
import { useEffect, useState } from "react";
import { Keyboard, KeyboardEvent } from "react-native";
export const useKeyboard = () => {
// TODO: uncomment to return the height
// const [ keyboardHeight, setKeyboardHeight ] = useState(0);
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
// const onKeyboardDidShow = (e) => setKeyboardHeight(e.endCoordinates.height);
// const onKeyboardDidHide = () => setKeyboardHeight(0);
// useEffect(() => {
// Keyboard.addListener('keyboardDidShow', onKeyboardDidShow);
// Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);
// return () => {
// Keyboard.remove('keyboardDidShow', onKeyboardDidShow);
// Keyboard.remove('keyboardDidHide', onKeyboardDidHide);
// };
// }, []);
// return [ keyboardHeight ];
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener("keyboardDidShow", () =>
setIsKeyboardVisible(true)
);
const keyboardDidHideListener = Keyboard.addListener("keyboardDidHide", () =>
setIsKeyboardVisible(false)
);
return () => {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
};
}, []);
// return true or false (keyboard is visible or not):
return isKeyboardVisible;
};
// Inorder to return true or false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment