@madeja-studio/telar
Version:
UI component library by Madeja Studio
59 lines (52 loc) • 1.83 kB
text/typescript
import type { KeyboardEventName } from 'react-native';
import React, { useEffect } from 'react';
import { Keyboard, Platform } from 'react-native';
const hideEvent: KeyboardEventName =
Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide';
/**
* Custom hook to manage keyboard state in a React Native application.
*
* Monitors the keyboard's visibility and height, updating the state accordingly.
*
* The code is directly extracted from the 10tap-editor repository:
* @link https://github.com/10play/10tap-editor/blob/main/src/utils/useKeyboard.tsx
*
* @return Object containing the keyboard visibility state and height.
* @property isKeyboardUp - Whether the keyboard is currently visible.
* @property keyboardHeight - The height of the keyboard when it is visible.
*
* @example
* const { isKeyboardUp, keyboardHeight } = useKeyboard();
*
* return (
* <View style={{ flex: 1, marginBottom: isKeyboardUp ? keyboardHeight : 0 }}>
* <TextInput placeholder="Type here..." />
* </View>
* );
*
*/
export const useKeyboard = () => {
const [isKeyboardUp, setIsKeyboardUp] = React.useState(false);
const [keyboardHeight, setKeyboardHeight] = React.useState(0);
useEffect(() => {
const willShowSubscription = Keyboard.addListener(
'keyboardWillShow',
() => {
setIsKeyboardUp(true);
}
);
const didShowSubscription = Keyboard.addListener('keyboardDidShow', (e) => {
setIsKeyboardUp(true);
setKeyboardHeight(e.endCoordinates.height);
});
const hideSubscription = Keyboard.addListener(hideEvent, () => {
setIsKeyboardUp(false);
});
return () => {
willShowSubscription.remove();
didShowSubscription.remove();
hideSubscription.remove();
};
}, []);
return { isKeyboardUp, keyboardHeight };
};