Skip to content

Instantly share code, notes, and snippets.

@Temzasse
Last active May 14, 2024 08:08
Show Gist options
  • Save Temzasse/38777abcf7d609b80677d3b5d8650b4d to your computer and use it in GitHub Desktop.
Save Temzasse/38777abcf7d609b80677d3b5d8650b4d to your computer and use it in GitHub Desktop.
A utility hook that listens to the virtual keyboard appearance and returns the dynamic height of the keyboard.
export function useVirtualKeyboard() {
const [isKeyboardOpen, setKeyboardOpen] = useState(false);
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const visualViewport = window.visualViewport;
if (visualViewport) {
const onResize = () => {
const focusedElement = document.activeElement as HTMLElement | null;
// Bail if no element is focused as that also means no input is focused
if (!focusedElement) return;
const isInputFocused =
focusedElement.tagName === 'INPUT' ||
focusedElement.tagName === 'TEXTAREA';
// Virtual keyboard should only be visible if an input is focused
if (isInputFocused && visualViewport.height < window.innerHeight) {
setKeyboardOpen(true);
setKeyboardHeight(window.innerHeight - visualViewport.height);
} else if (isKeyboardOpen) {
// Reset keyboard height if it was open
setKeyboardOpen(false);
setKeyboardHeight(0);
}
};
visualViewport.addEventListener('resize', onResize);
return () => {
visualViewport.removeEventListener('resize', onResize);
};
}
}, [isKeyboardOpen]);
return { keyboardHeight, isKeyboardOpen };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment