Forked from intergalacticspacehighway/useKeyboardBottomInset hook
Created
July 1, 2022 16:27
-
-
Save hirbod/1ce985a19e1f309561a49f628cc8b5b2 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 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 { 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