Created
May 24, 2023 14:43
-
-
Save ashwin1014/6bb7d7c1fd0800117547a2aa8bd5f65b to your computer and use it in GitHub Desktop.
Hook to get keyboard height in react native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
import { Keyboard, KeyboardEvent } from 'react-native'; | |
/** | |
* Shows height of keyboard when shown | |
*/ | |
function useKeyboardHeight() { | |
const [keyboardHeight, setKeyboardHeight] = useState(0); | |
function onKeyboardShow(event: KeyboardEvent) { | |
setKeyboardHeight(event.endCoordinates.height); | |
} | |
function onKeyboardHide() { | |
setKeyboardHeight(0); | |
} | |
useEffect(() => { | |
const onShow = Keyboard.addListener('keyboardDidShow', onKeyboardShow); | |
const onHide = Keyboard.addListener('keyboardDidHide', onKeyboardHide); | |
return () => { | |
onShow.remove(); | |
onHide.remove(); | |
}; | |
}, []); | |
return keyboardHeight; | |
} | |
export default useKeyboardHeight; |
^ the keyboardDidShow
and keyboardDidHide
events are not handled in android facebook/react-native#3468
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've noticed that the delay between
keyboardDidShow
andkeyboardWillShow
is sometimes severe enough to cause flickering. Refactoring your example, you can watch for either/or and make judgement calls: