Forked from intergalacticspacehighway/useKeyboardBottomInset hook
Created
February 28, 2023 11:31
-
-
Save mtzfactory/a17e3852b527c82e3b463a3fd62b2a6f to your computer and use it in GitHub Desktop.
Hook to get keyboard height in React Native and add bottom/padding inset on a view.
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 { Keyboard, Platform, KeyboardEvent } from 'react-native'; | |
const useKeyboardBottomInset = () => { | |
const [bottom, setBottom] = React.useState(0); | |
const subscriptions = React.useRef([]); | |
React.useEffect(() => { | |
function onKeyboardChange(e) { | |
if ( | |
e.startCoordinates && | |
e.endCoordinates.screenY < e.startCoordinates.screenY | |
) | |
setBottom(e.endCoordinates.height); | |
else setBottom(0); | |
} | |
if (Platform.OS === 'ios') { | |
subscriptions.current = [ | |
Keyboard.addListener('keyboardWillChangeFrame', onKeyboardChange), | |
]; | |
} else { | |
subscriptions.current = [ | |
Keyboard.addListener('keyboardDidHide', onKeyboardChange), | |
Keyboard.addListener('keyboardDidShow', onKeyboardChange), | |
]; | |
} | |
return () => { | |
subscriptions.current.forEach((subscription) => { | |
subscription.remove(); | |
}); | |
}; | |
}, [setBottom, subscriptions]); | |
return bottom; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment