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 @cqfw/react-native-orientation --save
Linking Native Dependencies
Automatic Linking
react-native link @cqfw/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.
Configuration
iOS
Add the following to your project's AppDelegate.m
:
#import "Orientation.h"
@implementation AppDelegate
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return [Orientation getOrientation];
}
@end
Android
Implement onConfigurationChanged
method in MainActivity.java
import android.content.Intent;
import android.content.res.Configuration;
public class MainActivity extends ReactActivity {
......
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = new Intent("onConfigurationChanged");
intent.putExtra("newConfig", newConfig);
this.sendBroadcast(intent);
}
......
}
Usage
To use the @cqfw/react-native-orientation
package in your codebase, you should use the Orientation module:
import Orientation from '@cqfw/react-native-orientation';
export default class AppScreen extends Component {
componentWillMount() {
const initial = Orientation.getInitialOrientation();
if (initial === 'PORTRAIT') {
} else {
}
},
componentDidMount() {
Orientation.lockToPortrait();
Orientation.addOrientationListener(this._orientationDidChange);
},
_orientationDidChange = (orientation) => {
if (orientation === 'LANDSCAPE') {
} else {
}
},
componentWillUnmount() {
Orientation.getOrientation((err, orientation) => {
console.log(`Current Device Orientation: ${orientation}`);
});
Orientation.removeOrientationListener(this._orientationDidChange);
}
render() {
return (
)
}
}
Orientation Events
addOrientationListener((orientation) => {});
orientation
will return one of the following values:
LANDSCAPE
PORTRAIT
PORTRAITUPSIDEDOWN
UNKNOWN
removeOrientationListener((orientation) => {});
addSpecificOrientationListener((specificOrientation) => {});
specificOrientation
will return one of the following values:
LANDSCAPE-LEFT
LANDSCAPE-RIGHT
PORTRAIT
PORTRAITUPSIDEDOWN
UNKNOWN
removeSpecificOrientationListener((specificOrientation) => {});
API
lockToPortrait()
lockToLandscape()
lockToLandscapeLeft()
lockToLandscapeRight()
unlockAllOrientations()
getOrientation((err, orientation) => {})
getSpecificOrientation((err, specificOrientation) => {})