Created
October 14, 2022 06:16
-
-
Save itispx/7cc2d7a8d73d2bf35ff848381e512688 to your computer and use it in GitHub Desktop.
useKeyboard hook
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 { useState, useEffect } from "react"; | |
import { Keyboard } from "react-native"; | |
const useKeyboard = (keyboardDefaultHeight = 250) => { | |
const [isKeyboardVisible, setKeyboardVisible] = useState(false); | |
const [keyboardHeight, setKeyboardHeight] = useState(keyboardDefaultHeight); | |
async function keyboardDidShowHandler(e) { | |
setKeyboardVisible(true); | |
setKeyboardHeight(e.endCoordinates.height); | |
} | |
async function keyboardDidHideHandler(e) { | |
setKeyboardVisible(false); | |
} | |
useEffect(() => { | |
const keyboardDidShowListener = Keyboard.addListener( | |
"keyboardDidShow", | |
keyboardDidShowHandler | |
); | |
const keyboardDidHideListener = Keyboard.addListener( | |
"keyboardDidHide", | |
keyboardDidHideHandler | |
); | |
return () => { | |
keyboardDidHideListener.remove(); | |
keyboardDidShowListener.remove(); | |
}; | |
}, []); | |
return { isKeyboardVisible, keyboardHeight }; | |
}; | |
export default useKeyboard; |
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 { useState, useEffect } from "react"; | |
import { Keyboard, KeyboardEvent } from "react-native"; | |
const useKeyboard = ( | |
keyboardDefaultHeight = 250 | |
): { isKeyboardVisible: boolean; keyboardHeight: number } => { | |
const [isKeyboardVisible, setKeyboardVisible] = useState(false); | |
const [keyboardHeight, setKeyboardHeight] = useState(keyboardDefaultHeight); | |
function keyboardDidShowHandler(e: KeyboardEvent) { | |
setKeyboardVisible(true); | |
setKeyboardHeight(e.endCoordinates.height); | |
} | |
function keyboardDidHideHandler() { | |
setKeyboardVisible(false); | |
} | |
useEffect(() => { | |
const keyboardDidShowListener = Keyboard.addListener( | |
"keyboardDidShow", | |
keyboardDidShowHandler | |
); | |
const keyboardDidHideListener = Keyboard.addListener( | |
"keyboardDidHide", | |
keyboardDidHideHandler | |
); | |
return () => { | |
keyboardDidHideListener.remove(); | |
keyboardDidShowListener.remove(); | |
}; | |
}, []); | |
return { isKeyboardVisible, keyboardHeight }; | |
}; | |
export default useKeyboard; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment