Skip to content

Instantly share code, notes, and snippets.

@petrbela
Last active January 17, 2025 20:50
Show Gist options
  • Save petrbela/d859308b22a09b4233fd72e26f2f9725 to your computer and use it in GitHub Desktop.
Save petrbela/d859308b22a09b4233fd72e26f2f9725 to your computer and use it in GitHub Desktop.
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