Dynamically Find Device Screen Orientation – Portrait or Landscape React Native Tutorial

Hello Guys, Through this tutorial I am going to describe you how we can detect device screen orientation dynamically on device screen orientation change in react native. Basically, it is possible through inbuilt react native library named as Dimensions . Dimensions API provides addEventListener  method which accepts a change  event to detect the orientation and this event fires when device screen orientation changes.

So let’s begin…

Step – 1: Import required components from react , react-native  packages.

Step – 2: Implement constructor  method.

Step – 3: Implement getOrientation  custom method which is responsible to get the device screen orientation. This getOrientation  custom method will be executed on both app initial load and device screen orientation change.

Explanation:

  • Whenever this getOrientation  method will be executed then it will make comparison between device’s width and device’s height and according to comparison’s result it will decide the device screen orientation and update the orientation  state variable.

Step – 4: Implement  componentDidMount method.

Explanation:

  • The change  event will be fired whenever device screen orientation will change and whenever this change  event will be fired then this.getOrientation  custom method will be executed to get the current and updated device screen orientation.

Step – 5: Implement  render method.

Step – 6: Implement styles for all required custom components.

Complete Source Code:

Step – 7: Execute react-native run-ios  to run app in iOS devices and / or execute react-native run-android  to run app in Android devices.

  • iOS Screenshots:

  • Android Screenshots:

Guys, If you have any queries then put your queries in the below comment section and thanks for reading my post. So enjoy and have fun… 😀

6 Comments

  1. Thanks for the article. But EventListener needs to be reset:
    componentWillUnMount() {
    Dimensions.removeEventListener(‘change’);
    }

  2. the thing is with this implementation you never know if it is landscape-right or left or portrait upside down

  3. Thanks. Just a tiny thing, it’s better to use componentWillMount() instead of ComponentDidMount()

Leave a Reply

Your email address will not be published. Required fields are marked *