Last active
July 31, 2024 12:11
-
-
Save louicoder/c33cc2a8e212073157cd6e68814c6107 to your computer and use it in GitHub Desktop.
React NAtive Hook for getting keyboard height
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, 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