Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
import { useRef } from 'react';
import { Keyboard } from 'react-native';
import { useSafeAreaFrame } from 'react-native-safe-area-context';
import { useEffect, useRef } from 'react';
import { Dimensions, Keyboard } from 'react-native';

const getIsPortrait = () => {
// 'screen' is the physical display size and is NOT affected by the soft keyboard.
// 'window'/safe-area frame shrink when the keyboard opens under adjustResize, which
// on small screens can make a keyboard-open look like a rotation and wrongly dismiss
// the keyboard right after it appears. Using 'screen' only reacts to real rotations.
const { width, height } = Dimensions.get('screen');
return width < height;
};

export const useCloseKeyboardWhenOrientationChanges = () => {
const { width, height } = useSafeAreaFrame();
const isPortrait = width < height;
const previousOrientation = useRef(isPortrait);
if (previousOrientation.current !== isPortrait) {
Keyboard.dismiss();
previousOrientation.current = isPortrait;
}
const isPortrait = useRef(getIsPortrait());

useEffect(() => {
const subscription = Dimensions.addEventListener('change', () => {
const portrait = getIsPortrait();
if (portrait !== isPortrait.current) {
isPortrait.current = portrait;
Keyboard.dismiss();
}
});
return () => subscription.remove();
}, []);
};
Loading