Get Device Orientation and Set Preferred Orientation in React Native

React Native Orientation

Hello guys, This is an Example to Get Device Orientation and Set Preferred Orientation in React Native. In this example we will see how can you control screen orientation and how can you get the rotation of the screen. Sometimes it becomes very much important to manage the orientation of the screen and if it is done properly then it will provide a user-friendly experience to your app users which is very much important for a developer.

If I have to mention the most general example of screen rotation or the orientation of the screen then a video-playing application like Youtube is the best example, it uses the screen very well using the orientation as users are very comfortable with portrait mode while searching and after playing a video it provides the landscape option to use your full screen.

In this example, we are going to see how to control screen rotation/orientation using react-native-orientation library.

You can also see How to Disable Screen Rotation in React Native.

Get Device Orientation

To get the orientation of the device react-native-orientation library provides two different categories:

Orientation

In the normal orientation we will get the following orientation as a response:

  • LANDSCAPE
  • PORTRAIT
  • PORTRAITUPSIDEDOWN
  • UNKNOWN

1. To get the Orientation any time use

Orientation.getOrientation((err, orientation) => {});

2. To add the Orientation Listener for the change in the orientation which will be triggered automatically when the orientation of the device changes

Orientation.addOrientationListener((orientation) => {});

3. To remove the Orientation Listener use

Orientation.removeOrientationListener();

Specific Orientation

In the specific orientation we will get the following orientation as a response:

  • LANDSCAPE-LEFT
  • LANDSCAPE-RIGHT
  • PORTRAIT
  • PORTRAITUPSIDEDOWN
  • UNKNOWN

1. To get the Specific Orientation at any time use

Orientation.getSpecificOrientation(
  (err, specificOrientation) => {}
);

2. To add the Specific Orientation Listener for the change in the orientation which will be triggered automatically when the orientation of the device changes

Orientation.addSpecificOrientationListener(
  (specificOrientation) => {}
);

3. To remove the Specific Orientation Listener use

Orientation.removeSpecificOrientationListener();

Set Preferred Orientation

Here are the all possible orientation which you can set using this library:

1. To Lock the View to Portrait Mode

Orientation.lockToPortrait()

2. To lock the View to Landscape Mode

Orientation.lockToLandscape()

3. To lock the View to Right Landscape Mode

Orientation.lockToLandscapeLeft()

4. To lock the View to Left Landscape Mode

Orientation.lockToLandscapeRight()

5. Unlocks any Previous Locked Orientations

Orientation.unlockAllOrientations()

I think this is enough to know about the library, now let’s move towards the example. In this example, we are going to see 7 buttons on the screen of which 2 buttons will be used to get the orientation and specific orientation of the device at any time and 5 buttons to set the preferred orientation.
We have also added orientation listeners for the screen so that the current orientation of the device will be visible on the screen.
Now let’s get started with the example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use Orientation we have to install react-native-orientation dependency.

To install the dependencies open the terminal and jump into your project

cd ProjectName

Now install the dependency

npm install react-native-orientation --save

Manual Changes for Android

Till react-native-orientation:3+ we need to make changes in build.gradle dependency to make the Android build.
Open node_modules/react-native-orientation/android/build.gradle
replace
compile "com.facebook.react:react-native:+"
with
implementation "com.facebook.react:react-native:+"
react-native-orientation-build-gradle

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install

Code to Get Device Orientation and Set Preferred Orientation in React Native

Now Open App.js in any code editor and replace the code with the following code

App.js

// Get Device Orientation and Set Preferred Orientation in React Native
// https://aboutreact.com/device-orientation/

// import React in our code
import React, {useState, useEffect} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ScrollView,
} from 'react-native';

// import Orientation
import Orientation from 'react-native-orientation';

const App = () => {
  const [currentOrientation, setCurrentOrientation] = useState('');

  useEffect(() => {
    // Getting initial Orientation
    const initial = Orientation.getInitialOrientation();
    setCurrentOrientation('Current Device Orientation: ' + initial);

    // Listner for orientation change LANDSCAPE / PORTRAIT
    Orientation.addOrientationListener(orientationChange);

    return () => {
      // Remember to remove listener
      Orientation.removeOrientationListener(orientationChange);
    };
  }, []);

  const orientationChange = (orientation) => {
    setCurrentOrientation(
      'Current Device Orientation: ' + orientation
    );
  };

  const getCurrentOrientation = () => {
    Orientation.getOrientation((err, orientation) => {
      alert('Orientation: ' + orientation);
    });
  };

  return (
    <SafeAreaView style={styles.container}>
      <View>
        <Text style={styles.titleText}>
          Get and Set Device Orientation in React Native
        </Text>
        <ScrollView>
          <View style={styles.container}>
            <Text style={styles.textLarge}>
              Example of React Native Orientation
            </Text>
            <Text style={styles.textSmall}>
              {currentOrientation}
            </Text>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={getCurrentOrientation}>
              <Text style={styles.buttonTextStyle}>
                get Current Orientation
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() => Orientation.lockToPortrait()}>
              <Text style={styles.buttonTextStyle}>
                Locks the View to Portrait Mode
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() => Orientation.lockToLandscape()}>
              <Text style={styles.buttonTextStyle}>
                Locks the View to Landscape Mode
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() => Orientation.lockToLandscapeLeft()}>
              <Text style={styles.buttonTextStyle}>
                Locks the View to Right Landscape Mode
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() => Orientation.lockToLandscapeRight()}>
              <Text style={styles.buttonTextStyle}>
                Locks the View to Left Landscape Mode
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() => Orientation.unlockAllOrientations()}>
              <Text style={styles.buttonTextStyle}>
                Unlocks any Previous Locked Orientations
              </Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    justifyContent: 'center',
  },
  titleText: {
    fontSize: 22,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  buttonStyle: {
    justifyContent: 'center',
    marginTop: 15,
    padding: 10,
    backgroundColor: '#8ad24e',
    marginRight: 2,
    marginLeft: 2,
  },
  buttonTextStyle: {
    color: '#fff',
    textAlign: 'center',
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

If you face any multidex-related error then you can follow these instructions.

Output Screenshots

Img   Img   Img
Img   Img   Img
Img   Img   Img

This is how you can Get Device Orientation and Set Preferred Orientation in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

4 thoughts on “Get Device Orientation and Set Preferred Orientation in React Native”

  1. Hello Snehal, great article from you.
    I am building a camera application and there i want to shoot both landscape and portrait videos,
    the problem I am facing is that I don’t want my whole screen to be rotated while the device gets rotated, instead I want my camera screen to be locked on portrait mode and rotate the icons by using “Animated”, but while locking to portrait I am not able to get the “onOrientationChange” eventListener
    so is there any way to get onOrientationChange listeners while locking to portrait?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.