Created
August 10, 2021 04:54
-
-
Save intergalacticspacehighway/f60aaaf773d1c955c53e27a2ad099bd5 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