user8523516
user8523516

Reputation:

How to Get Current Window height & width after change Orientation in React-Native?

I used Dimensions class for get Current Window Width & Height. its Proper works when first time lunch screen buts its now working with change Orientation.(Not Height-Width get When Change Orientation)

import React from 'react';
import {
    View,
    Text,
    Dimensions
} from 'react-native';

const window = Dimensions.get('window');

let aspectRatio = window.Width / window.Height;

export default class Home extends PureComponent {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }>
                <Text style={{ fontSize: 22}}>Height is {aspectRatio}</Text>
            </View>
        )
    }// end of render
};

Upvotes: 6

Views: 8233

Answers (1)

Ray
Ray

Reputation: 9674

RN gave you an event listener that you can use whenever a property within the Dimensions object changes. You can read about it more here.

The event will output an object that has the screen dimensions info and the window. You can then simply update the state whenever an orientation occurs.

Dimensions.addEventListener('change', (e) => {
  const { width, height } = e.window;
  this.setState({width, height});
})

Upvotes: 9

Related Questions