React Native Orientation
Listen to device orientation changes in React Native applications and programmatically set preferred orientation on a per screen basis. Works on both Android and iOS.
Installing
npm install react-native-orientation --save
Linking Native Dependencies
Automatic Linking
react-native link react-native-orientation
Please note that you still need to manually configure a couple files even when using automatic linking. Please see the 'Configuration' section below. You will also need to restart your simulator before the package will work properly.
Manual Linking
iOS
- Add
node_modules/react-native-orientation/iOS/RCTOrientation.xcodeproj
to your xcode project, usually under theLibraries
group - Add
libRCTOrientation.a
(fromProducts
underRCTOrientation.xcodeproj
) to build target'sLinked Frameworks and Libraries
list - Add
$(SRCROOT)/node_modules/react-native-orientation/iOS/RCTOrientation/
toProject Name
->Build Settings
->Header Search Paths
Android
-
In
android/setting.gradle
... include ':react-native-orientation', ':app' project(':react-native-orientation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-orientation/android')
-
In
android/app/build.gradle
... dependencies { ... compile project(':react-native-orientation') }
-
Register module in
MainApplication.java
// <--- import
Configuration
iOS
Add the following to your project's AppDelegate.m
:
// <--- import
Android
Implement onConfigurationChanged
method in MainActivity.java
// <--- import // <--- import
Usage
To use the react-native-orientation
package in your codebase, you should use the Orientation module:
;
// ... { // The getOrientation method is async. It happens sometimes that // you need the orientation at the moment the JS runtime starts running on device. // `getInitialOrientation` returns directly because its a constant set at the // beginning of the JS runtime. const initial = Orientation; if initial === 'PORTRAIT' // do something else // do something else } { // this locks the view to Portrait Mode Orientation; // this locks the view to Landscape Mode // Orientation.lockToLandscape(); // this unlocks any previous locks to all Orientations // Orientation.unlockAllOrientations(); Orientation; } { if orientation === 'LANDSCAPE' // do something with landscape layout else // do something with portrait layout } { Orientation; // Remember to remove listener Orientation; } { // ... return // ... }
Orientation Events
;
orientation
will return one of the following values:
LANDSCAPE
PORTRAIT
PORTRAITUPSIDEDOWN
UNKNOWN
;
;
specificOrientation
will return one of the following values:
LANDSCAPE-LEFT
LANDSCAPE-RIGHT
PORTRAIT
PORTRAITUPSIDEDOWN
UNKNOWN
;
API
lockToPortrait()
lockToLandscape()
lockToLandscapeLeft()
lockToLandscapeRight()
unlockAllOrientations()
getOrientation((err, orientation) => {})
getSpecificOrientation((err, specificOrientation) => {})