react-native: useWindowDimensions() returns swapped height and width in iOS

Description

When tested with iPad simulator, the useWindowDimensions(...) hook returns incorrect width and height.

React Native version:

Run react-native info in your terminal and copy the results here.

info Fetching system and libraries information...
System:
    OS: macOS 10.15.5
    CPU: (4) x64 Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
    Memory: 24.79 MB / 8.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 12.18.0 - /var/folders/k_/twn4fnrn6g56kn0xjlkp3zx00000gn/T/yarn--1594122179123-0.9086048405049534/node
    Yarn: 1.22.4 - /var/folders/k_/twn4fnrn6g56kn0xjlkp3zx00000gn/T/yarn--1594122179123-0.9086048405049534/yarn
    npm: 6.14.5 - /usr/local/bin/npm
    Watchman: Not Found
  Managers:
    CocoaPods: 1.9.3 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 13.5, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2
    Android SDK:
      API Levels: 23, 26, 28, 29
      Build Tools: 27.0.3, 28.0.3, 29.0.2, 30.0.0
      System Images: android-29 | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.0 AI-193.6911.18.40.6514223
    Xcode: 11.5/11E608c - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_242-release - /usr/bin/javac
    Python: 2.7.16 - /usr/bin/python
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.11.0 => 16.11.0 
    react-native: ^0.62.2 => 0.62.2 
  npmGlobalPackages:
    *react-native*: Not Found
✨  Done in 11.68s.

Steps To Reproduce

Provide a detailed list of steps that reproduce the issue.

  1. Use react-native init to create a new project.
  2. Edit App.js with the following code
    import React from "react";
    import { Text, View, useWindowDimensions } from "react-native";
    
    export const App = () => {
      const { width, height } = useWindowDimensions();
    
      return (
        <View
          style={{
            width: "100%",
            height: "100%",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Text>{width > height ? "landscape" : "portrait"}</Text>
          <Text>{`width: ${width}, height: ${height}`}</Text>
        </View>
      );
    };
    

Expected Results

  1. At the first time I rotate the simulator to landscape, it should display "landscape" instead of nothing happens.
  2. At the second time the simulator rotates back to portrait position, it should render "portrait" on the screen.
  3. At the second time I rotate from portrait to landscape, it should display "landscape" instead of "portrait".

Snack, code example, screenshot, or link to a repository:

It is not easy to show device orientation features in snack, I’ll attach screen recordings below.

Screen Recording 2020-07-07 at 7 39 07 PM

You may download the original video to pause for the rendered text. Screen Recording 2020-07-07 at 7.39.07 PM.zip

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 7
  • Comments: 43 (15 by maintainers)

Commits related to this issue

Most upvoted comments

https://appandflow.github.io/react-native-safe-area-context/ const { width, height } = useSafeAreaFrame() instead of const { width, height } = useWindowDimensions()

For me, useWindowDimensions had a delay after some rotations showing me landscape when changing to portrait.

@chrisglein Android is working fine.

iOS is behaving strangely, not a simple unresponsive but kind of a “delayed” state.

  1. You start the app in portrait
  2. The first time it changes from portrait to landscape, nothing happens
  3. You rotate back to portrait
  4. It now returns landscape (width > height)
  5. Now you rotate to landscape again
  6. It now returns portrait (width < height)

Since step 3 the behaviour repeats, only by re-launching the app could you reproduce step 1 and 2.

https://appandflow.github.io/react-native-safe-area-context/ const { width, height } = useSafeAreaFrame() instead of const { width, height } = useWindowDimensions() For me, useWindowDimensions had a delay after some rotations showing me landscape when changing to portrait.

Unfortunately this does not work well with React Native Web, so no option on cross platform Apps.

For web you can just add a .web.ts override with the original useWindowDimensions.

But the solution I’ve finally landed on, and the only one that works on ARM Mac builds for me (“Mac - Designed for iPad”), is adding an invisible View in the root and measuring its size, like this:

import { useCallback } from 'react'
import { LayoutChangeEvent, StyleSheet, View } from 'react-native'

import { create } from 'zustand'

interface DimensionsStore {
  width: number
  height: number
  setDimensions: (dimensions: { width: number; height: number }) => void
}

export const useDimensionsStore = create<DimensionsStore>((set) => ({
  width: 0,
  height: 0,
  setDimensions: ({ width, height }) => set({ width, height }),
}))

export function DimensionsMeasurer() {
  const { setDimensions } = useDimensionsStore()

  // https://github.com/facebook/react-native/issues/36118#issuecomment-1500981629
  const handleLayout = useCallback(
    (event: LayoutChangeEvent) => {
      setDimensions(event.nativeEvent.layout)
    },
    [setDimensions],
  )

  return <View onLayout={handleLayout} style={StyleSheet.absoluteFill} />
}

Any update on this one? It also happens in my project in iPad.

Might be this: https://github.com/facebook/react-native/pull/46353

Your alternative solution works well in my project.

Thank you @AlejandroRM-DEV

If anyone is experiencing this, here’s the patch my team used for react-native 0.76.5

diff --git a/node_modules/react-native/React/CoreModules/RCTDeviceInfo.mm b/node_modules/react-native/React/CoreModules/RCTDeviceInfo.mm
index 454a325..018b2f3 100644
--- a/node_modules/react-native/React/CoreModules/RCTDeviceInfo.mm
+++ b/node_modules/react-native/React/CoreModules/RCTDeviceInfo.mm
@@ -54,6 +54,11 @@ - (void)initialize

   _currentInterfaceDimensions = [self _exportedDimensions];

+    [[NSNotificationCenter defaultCenter] addObserver:self
+                                             selector:@selector(interfaceOrientationDidChange)
+                                                 name:UIApplicationDidChangeStatusBarOrientationNotification
+                                               object:nil];
+
   [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(interfaceOrientationDidChange)
                                                name:UIApplicationDidBecomeActiveNotification

This was removed somewhere in between 0.73.6 and 0.76.5. UIApplicationDidChangeStatusBarOrientationNotification is deprecated on iOS, but in the meantime, this works!

@gerwld A simple custom hook is not enough. It’s likely caused by a delayed orientation change event, and in turn lead to a stale state returned by Dimensions.get('window') and useWindowDimensions.

You may try building a custom Native Module that directly listens to the orientation change event.

This issue is still valid to this date.

If any anyone is interested and want more information to start working, please let me know.

Only workaround is to work with custom native modules.

Even DeviceInfo uses the same logic for landscape detection than native values, the potential affected users is sizeable in that sense.