james murphy
james murphy

Reputation: 1805

Dimensions.get('screen') not working in React Native

Im using react-native dimensions to get dimensions of screen and determine if user is in portrait or landscape mode.....however Dimensions.get('screen').height is ALWAYS coming back as the longer of the 2 sides, even when in landscape mode.....i.e. Dimensions.get('screen').height is always coming back as larger than Dimensions.get('screen').width, even when in landscape mode

constructor(props) {
    super(props);
    this.state = {
      orientation: (Dimensions.get('screen').height >= Dimensions.get('screen').width ? 'portrait' : 'landscape')
    };

    Dimensions.addEventListener('change', () => {
      let orientation = (Dimensions.get('screen').height >= Dimensions.get('screen').width ? 'portrait' : 'landscape');
      this.setState({
        orientation: orientation
      });
    });
  }

Upvotes: 2

Views: 2109

Answers (1)

lonecruisader
lonecruisader

Reputation: 438

use useWindowDimensions(). Just put something like this in your root component :

const SCREEN_WIDTH = useWindowDimensions().width;
const SCREEN_HEIGHT = useWindowDimensions().height;
return (
    <View style={{ width: SCREEN_WIDTH, minHeight: SCREEN_HEIGHT}} >
        //the rest of your app
    </View>
);

Upvotes: 1

Related Questions