Last active
June 12, 2024 04:43
-
-
Save btoo/7f713027e8bcf8f4b3c94b5ce51d3917 to your computer and use it in GitHub Desktop.
react native keyboard height hook
This file contains hidden or 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 } from "react"; | |
import { Keyboard } from "react-native"; | |
import { useState } from "./mounted"; | |
export function useKeyboardHeight() { | |
const [keyboardHeight, setKeyboardHeight] = useState(0); | |
useEffect(() => { | |
const showSubscription = Keyboard.addListener('keyboardDidShow', e => setKeyboardHeight(e.endCoordinates.height)); | |
const hideSubscription = Keyboard.addListener('keyboardWillHide', () => setKeyboardHeight(0)); | |
return () => { | |
showSubscription.remove(); | |
hideSubscription.remove(); | |
} | |
}, [setKeyboardHeight]); | |
return keyboardHeight; | |
} |
keyboardDidHide instead of keyboardWillHide dependency [setKeyboardHeight] in useEffect is not needed [ ]
I think it is better to use KeyboardWillHide
and KeyboardWillShow
as this is going to remove the delay in styles, if applying, based on the keyboard height.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
keyboardDidHide instead of keyboardWillHide
dependency [setKeyboardHeight] in useEffect is not needed [ ]