Jose Cabrera Zuniga
Jose Cabrera Zuniga

Reputation: 2619

React Native Dimensions not working on rotation

I am running the code posted (for Class Component) at:

https://reactnative.dev/docs/dimensions

Yet, at the Android Studio simulator, If I "rotate" the device the dimension's values do not change i.e. I was expecting that the height and width could change with the rotation but this is not happening. Any ideas why?

According to the info posted at the previous link it says:

Although dimensions are available immediately, they may change (e.g due to device rotation, foldable devices etc) so any rendering logic or styles that depend on these constants should try to call this function on every render, rather than caching the value (for example, using inline styles rather than setting a value in a StyleSheet).

I also tried using using useWindowDimensions but this is limited to functional react components.

So far, I can not find a reliable way to detect if an Android device rotated using React-Native and class components :-(

Note: This problem also happens with React Function Component

Upvotes: 3

Views: 2463

Answers (3)

Raul Glez Rdguez
Raul Glez Rdguez

Reputation: 321

Try: https://reactnative.dev/docs/usewindowdimensions It works for me

import { useWindowDimensions } from 'react-native';


const { height, width } = useWindowDimensions();

Upvotes: 7

lastant
lastant

Reputation: 161

My problem on 0.61.5 was not that the values were not correct, but that the view was not re-rendered at all after the rotation, so I added this to the constructor() and it worked:

Dimensions.addEventListener('change', () => {
  this.setState({});
});

Upvotes: 1

mradex77
mradex77

Reputation: 137

I had the same problem. Upgrading react-native to version 0.64.2 fixed it.

Upvotes: 1

Related Questions