Last active
January 17, 2025 20:50
-
-
Save petrbela/d859308b22a09b4233fd72e26f2f9725 to your computer and use it in GitHub Desktop.
useWindowDimensions fix for https://github.com/facebook/react-native/issues/29290
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 { | |
Orientation, | |
addOrientationChangeListener, | |
getOrientationAsync, | |
removeOrientationChangeListener, | |
} from 'expo-screen-orientation' | |
import { useEffect, useState } from 'react' | |
import { Dimensions } from 'react-native' | |
/** | |
* Return actual window dimensions even when orientation changes. | |
* | |
* @see https://github.com/facebook/react-native/issues/29290 | |
* @returns window dimensions | |
*/ | |
export function useWindowDimensions() { | |
const [dimensions, setDimensions] = useState(Dimensions.get('window')) | |
useEffect(() => { | |
getOrientationAsync().then((orientation) => { | |
setDimensions(fixDimensions(orientation)) | |
}) | |
const listener = addOrientationChangeListener(({ orientationInfo }) => { | |
setDimensions(fixDimensions(orientationInfo.orientation)) | |
}) | |
return () => { | |
removeOrientationChangeListener(listener) | |
} | |
}, []) | |
return dimensions | |
} | |
function fixDimensions(orientation: Orientation) { | |
let window = Dimensions.get('window') | |
if ( | |
(orientation === Orientation.LANDSCAPE_LEFT || | |
orientation === Orientation.LANDSCAPE_RIGHT) && | |
window.width < window.height | |
) { | |
return { ...window, width: window.height, height: window.width } | |
} else if ( | |
(orientation === Orientation.PORTRAIT_UP || | |
orientation === Orientation.PORTRAIT_DOWN) && | |
window.width > window.height | |
) { | |
return { ...window, width: window.height, height: window.width } | |
} | |
return window | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment