### Install React Native Orientation Locker
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Instructions for installing the react-native-orientation-locker package using either yarn or npm. This step is required before using the library's functionalities.
```bash
# Using yarn (RN 0.60+)
yarn add react-native-orientation-locker
# Using npm
npm install react-native-orientation-locker
```
--------------------------------
### Install react-native-orientation-locker using Yarn
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Installs the react-native-orientation-locker package using Yarn. For React Native versions 0.60 and above, a simple add command is sufficient. For older versions (0.59 and below), an additional linking step is required.
```bash
yarn add react-native-orientation-locker
```
```bash
yarn add react-native-orientation-locker
react-native link react-native-orientation-locker
```
--------------------------------
### Orientation Query Functions
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Functions to get the current orientation and device orientation.
```APIDOC
## Orientation Query Functions
### Description
Functions to retrieve the current screen orientation and device orientation, as well as the auto-rotate state.
### Method
`getOrientation(callback)`
`getDeviceOrientation(callback)`
`getAutoRotateState(callback)` (Android only)
`isLocked()`
### Endpoint
N/A (These are direct function calls)
### Parameters
#### `getOrientation` and `getDeviceOrientation`
- **callback** (function) - A function that receives the orientation string as an argument.
#### `getAutoRotateState`
- **callback** (function) - A function that receives the auto-rotate state (boolean) as an argument.
### Request Example
```javascript
OrientationLocker.getOrientation((orientation) => {
console.log('Current orientation:', orientation);
});
OrientationLocker.getDeviceOrientation((deviceOrientation) => {
console.log('Device orientation:', deviceOrientation);
});
// Android only
OrientationLocker.getAutoRotateState((state) => {
console.log('Auto-rotate state:', state);
});
const lockedStatus = OrientationLocker.isLocked();
console.log('Is orientation locked?', lockedStatus);
```
### Response
#### Success Response (Callback)
- **orientation** (string) - The current screen orientation. Possible values: `PORTRAIT`, `LANDSCAPE-LEFT`, `LANDSCAPE-RIGHT`, `PORTRAIT-UPSIDEDOWN`, `FACE-UP`, `FACE-DOWN`, `UNKNOWN`.
- **deviceOrientation** (string) - The current device orientation. Same possible values as `orientation`.
- **state** (boolean) - The auto-rotate state (true if enabled, false if disabled). (Android only)
- **isLocked()** (boolean) - Returns true if the orientation is locked by this library, false otherwise.
### Notes
- `PORTRAIT-UPSIDEDOWN` is not supported on iOS.
- `FACE-UP` and `FACE-DOWN` are only supported on iOS and Windows.
```
--------------------------------
### Get Initial Orientation in React Native
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Synchronously returns the orientation of the application at startup. This function is not asynchronous and provides an immediate value, unlike `getOrientation`. It's useful for setting initial layout configurations.
```javascript
import Orientation from 'react-native-orientation-locker';
function App() {
// Get initial orientation synchronously - available immediately
const initialOrientation = Orientation.getInitialOrientation();
const [layout, setLayout] = useState(
initialOrientation === 'PORTRAIT' ? 'vertical' : 'horizontal'
);
useEffect(() => {
console.log('App started in:', initialOrientation);
// Configure initial layout based on starting orientation
if (initialOrientation === 'LANDSCAPE-LEFT' || initialOrientation === 'LANDSCAPE-RIGHT') {
setLayout('horizontal');
}
}, []);
return ;
}
```
--------------------------------
### Implement Orientation Control and Monitoring in React Native
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
This example demonstrates how to use hooks like useOrientationChange and useLockListener to track orientation state, and imperative methods to lock or unlock the screen orientation. It requires the react-native-orientation-locker library and is designed for React Native applications.
```javascript
import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, ScrollView, StyleSheet, Platform } from 'react-native';
import Orientation, { useOrientationChange, useDeviceOrientationChange, useLockListener } from 'react-native-orientation-locker';
export default function App() {
const [isLocked, setIsLocked] = useState(false);
const [uiOrientation, setUiOrientation] = useState('UNKNOWN');
const [deviceOrientation, setDeviceOrientation] = useState('UNKNOWN');
const [lockState, setLockState] = useState('UNKNOWN');
useOrientationChange((o) => setUiOrientation(o));
useDeviceOrientationChange((o) => setDeviceOrientation(o));
useLockListener((o) => setLockState(o));
useEffect(() => {
const initial = Orientation.getInitialOrientation();
setIsLocked(Orientation.isLocked());
if (Platform.OS === 'android') {
Orientation.getAutoRotateState((enabled) => console.log('Auto-rotate enabled:', enabled));
}
}, []);
const updateLockState = () => setIsLocked(Orientation.isLocked());
return (
Orientation Locker DemoUI Orientation: {uiOrientation}Device Orientation: {deviceOrientation}Locked: {isLocked ? 'Yes' : 'No'}Lock State: {lockState} { Orientation.lockToPortrait(); updateLockState(); }}>
Lock to Portrait { Orientation.lockToLandscape(); updateLockState(); }}>
Lock to Landscape { Orientation.unlockAllOrientations(); updateLockState(); }}>
Unlock All Orientations
);
}
const styles = StyleSheet.create({
container: { flexGrow: 1, padding: 20, paddingTop: 50, alignItems: 'center' },
title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
statusBox: { backgroundColor: '#f0f0f0', padding: 15, borderRadius: 10, marginBottom: 20, width: '100%' },
button: { backgroundColor: '#007AFF', padding: 15, borderRadius: 8, marginVertical: 5, width: '100%', alignItems: 'center' },
unlockButton: { backgroundColor: '#34C759' }
});
```
--------------------------------
### Lock Device Orientation using OrientationLocker
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Demonstrates how to import orientation constants and use the OrientationLocker component to programmatically lock the device screen to specific orientations. It includes a functional component example that toggles between different orientation states via button presses.
```javascript
import {
OrientationLocker,
UNLOCK,
PORTRAIT,
LANDSCAPE,
LANDSCAPE_LEFT,
LANDSCAPE_RIGHT,
PORTRAIT_UPSIDE_DOWN,
ALL_ORIENTATIONS_BUT_UPSIDE_DOWN
} from 'react-native-orientation-locker';
function OrientationDemo() {
const [mode, setMode] = useState(PORTRAIT);
return (
);
}
```
--------------------------------
### Lock Screen to Portrait Orientation
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Demonstrates how to lock the screen orientation to portrait mode using `Orientation.lockToPortrait()`. This is useful for screens that should always be displayed upright. The example includes unlocking all orientations when the component unmounts.
```javascript
import Orientation from 'react-native-orientation-locker';
// Lock to portrait on component mount
function VideoPlayerScreen() {
useEffect(() => {
// Lock to portrait when screen mounts
Orientation.lockToPortrait();
// Unlock when component unmounts
return () => {
Orientation.unlockAllOrientations();
};
}, []);
return Portrait-locked content;
}
```
--------------------------------
### Lock Screen to Portrait Upside Down (Android/Windows)
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Illustrates how to lock the screen to the portrait upside-down orientation. This functionality is specifically supported on Android and Windows platforms. The example includes a platform check and ensures orientation is reset upon component unmount.
```javascript
import Orientation from 'react-native-orientation-locker';
import { Platform } from 'react-native';
function UpsideDownScreen() {
useEffect(() => {
if (Platform.OS === 'android' || Platform.OS === 'windows') {
Orientation.lockToPortraitUpsideDown();
}
return () => Orientation.unlockAllOrientations();
}, []);
return Upside down content;
}
```
--------------------------------
### Lock Screen to Landscape Orientation
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Shows how to lock the screen orientation to landscape mode, allowing rotation between landscape-left and landscape-right. This is commonly used for video players or games. The example ensures orientation is unlocked on component unmount.
```javascript
import Orientation from 'react-native-orientation-locker';
function FullscreenVideoPlayer({ onClose }) {
useEffect(() => {
// Lock to landscape for video playback
Orientation.lockToLandscape();
return () => {
Orientation.unlockAllOrientations();
};
}, []);
return (
Close
);
}
```
--------------------------------
### Get Device Orientation in React Native
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Asynchronously retrieves the physical orientation of the device. It can return additional values like 'FACE-UP' and 'FACE-DOWN' on iOS and Windows, in addition to standard orientation values. This function is asynchronous and requires a callback.
```javascript
import Orientation from 'react-native-orientation-locker';
function DevicePositionTracker() {
const [devicePosition, setDevicePosition] = useState('UNKNOWN');
useEffect(() => {
// Get physical device orientation
Orientation.getDeviceOrientation((deviceOrientation) => {
console.log('Device Position:', deviceOrientation);
setDevicePosition(deviceOrientation);
// deviceOrientation: 'PORTRAIT' | 'LANDSCAPE-LEFT' | 'LANDSCAPE-RIGHT' |
// 'PORTRAIT-UPSIDEDOWN' | 'FACE-UP' | 'FACE-DOWN' | 'UNKNOWN'
});
}, []);
return Device is: {devicePosition};
}
```
--------------------------------
### Lock Screen to Landscape Right Orientation
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Provides an example of locking the screen to the landscape-right orientation (camera on the right, home button on the left). This is the opposite of landscape-left and can be used when a specific fixed landscape position is needed. The code includes unlocking on component unmount.
```javascript
import Orientation from 'react-native-orientation-locker';
// Lock to landscape-right
function DocumentScanner() {
useEffect(() => {
// Camera right, home button left
Orientation.lockToLandscapeRight();
return () => Orientation.unlockAllOrientations();
}, []);
return ;
}
```
--------------------------------
### Get Current UI Orientation in React Native
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Asynchronously retrieves the current UI orientation of the device. It returns one of the predefined orientation strings: 'PORTRAIT', 'LANDSCAPE-LEFT', 'LANDSCAPE-RIGHT', 'PORTRAIT-UPSIDEDOWN', or 'UNKNOWN'. This function is asynchronous and takes a callback function as an argument.
```javascript
import Orientation from 'react-native-orientation-locker';
function OrientationDisplay() {
const [currentOrientation, setCurrentOrientation] = useState('UNKNOWN');
useEffect(() => {
// Get current UI orientation asynchronously
Orientation.getOrientation((orientation) => {
console.log('Current UI Orientation:', orientation);
setCurrentOrientation(orientation);
// orientation: 'PORTRAIT' | 'LANDSCAPE-LEFT' | 'LANDSCAPE-RIGHT' | 'PORTRAIT-UPSIDEDOWN' | 'UNKNOWN'
});
}, []);
return Current orientation: {currentOrientation};
}
```
--------------------------------
### Manually link OrientationPackage to MainApplication.java
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
This snippet shows how to manually add the OrientationPackage to the MainApplication.java file if autolinking fails or is not supported. This is necessary for the library to be recognized by the Android application.
```java
//...\nimport org.wonday.orientation.OrientationPackage;\n @Override\n protected List getPackages() {\n @SuppressWarnings("UnnecessaryLocalVariable")\n List packages = new PackageList(this).getPackages();\n // Packages that cannot be autolinked yet can be added manually here, for example:\n // packages.add(new MyReactNativePackage());\n packages.add(new OrientationPackage());\n return packages;\n }\n//...
```
--------------------------------
### Manage orientation imperatively with Orientation API
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Demonstrates using the Orientation class to lock screen orientation, check initial state, and register event listeners for orientation changes within React class components.
```javascript
import Orientation from 'react-native-orientation-locker';
_onOrientationDidChange = (orientation) => {
if (orientation == 'LANDSCAPE-LEFT') {
// Handle landscape left
} else {
// Handle portrait
}
};
componentDidMount() {
Orientation.lockToPortrait();
Orientation.addOrientationListener(this._onOrientationDidChange);
}
componentWillUnmount() {
Orientation.removeOrientationListener(this._onOrientationDidChange);
}
```
--------------------------------
### Control orientation declaratively with OrientationLocker component
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Shows how to use the OrientationLocker component to manage orientation settings declaratively. Props are merged based on mount order, similar to the StatusBar component.
```javascript
import { OrientationLocker, PORTRAIT, LANDSCAPE } from "react-native-orientation-locker";
export default function App() {
return (
console.log('onChange', orientation)}
/>
);
}
```
--------------------------------
### Register OrientationActivityLifecycle in MainApplication.java
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Registers the `OrientationActivityLifecycle` callbacks in the `MainApplication.java` file for Android. This integration ensures that the orientation locker is properly initialized and managed throughout the application's lifecycle.
```java
import org.wonday.orientation.OrientationActivityLifecycle;\n @Override\n public void onCreate() {\n registerActivityLifecycleCallbacks(OrientationActivityLifecycle.getInstance());\n }
```
--------------------------------
### Handle Orientation Type Events
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Provides a pattern for processing orientation strings returned by the library's listeners. This switch-case logic maps platform-specific orientation constants to custom application states.
```javascript
import Orientation, { OrientationType } from 'react-native-orientation-locker';
function handleOrientation(orientation) {
switch (orientation) {
case 'PORTRAIT':
return 'vertical';
case 'LANDSCAPE-LEFT':
return 'horizontal-left';
case 'LANDSCAPE-RIGHT':
return 'horizontal-right';
case 'PORTRAIT-UPSIDEDOWN':
return 'vertical-inverted';
case 'FACE-UP':
return 'flat-up';
case 'FACE-DOWN':
return 'flat-down';
case 'UNKNOWN':
default:
return 'unknown';
}
}
```
--------------------------------
### Orientation Control Functions
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Functions to configure and lock the screen orientation.
```APIDOC
## Configuration
### Description
Configures orientation locking behavior. Currently supports disabling face up/down detection on iOS.
### Method
`configure`
### Parameters
#### Request Body
- **disableFaceUpDown** (boolean) - Optional - If true, disables face up/down orientation detection on iOS.
### Request Example
```javascript
OrientationLocker.configure({ disableFaceUpDown: true });
```
## Locking Functions
### Description
Functions to lock the screen to specific orientations.
### Method
`lockToPortrait()`
`lockToLandscape()`
`lockToLandscapeLeft()`
`lockToLandscapeRight()`
`lockToPortraitUpsideDown()` (Android and Windows only)
`lockToAllOrientationsButUpsideDown()` (iOS only)
`unlockAllOrientations()`
### Endpoint
N/A (These are direct function calls)
### Parameters
None for these functions.
### Request Example
```javascript
OrientationLocker.lockToPortrait();
OrientationLocker.lockToLandscapeLeft(); // Locks to camera left home button right
OrientationLocker.lockToLandscapeRight(); // Locks to camera right home button left
```
### Response
None (These functions perform actions directly).
```
--------------------------------
### Configure Android Manifest for Orientation Changes
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Updates the AndroidManifest.xml file to include `android:configChanges` for handling keyboard, keyboard hidden, orientation, and screen size changes. This is crucial for the orientation locker to function correctly on Android devices.
```xml
\n\n ....\n\n
```
--------------------------------
### Add Orientation.h to iOS Bridging Header
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Includes the Orientation.h header file in the project's bridging header for iOS projects (RN 0.77 and above). This allows Swift code to interact with the Objective-C methods provided by the orientation locker library.
```objectivec
// ...\n#import "Orientation.h"\n// ...
```
--------------------------------
### Register Orientation Activity Lifecycle on Android
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
This code snippet demonstrates how to register the OrientationActivityLifecycle in the onCreate method of your MainApplication on Android. This is necessary for the library to function correctly on Android devices.
```java
import org.wonday.orientation.OrientationActivityLifecycle;
@Override
public void onCreate() {
...
+ registerActivityLifecycleCallbacks(OrientationActivityLifecycle.getInstance());
}
```
--------------------------------
### Configure iOS AppDelegate.swift for Orientation Locker
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Adds the necessary method to the AppDelegate.swift file in iOS projects (RN 0.77 and above) to handle orientation locking using the react-native-orientation-locker library. This ensures the application respects the orientation settings.
```swift
// ...\n@main\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n // ...\n\n // required for react-native-orientation-locker\n func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {\n return Orientation.getOrientation()\n }\n}\n// ...
```
--------------------------------
### Handle orientation changes with React Hooks
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Utilizes custom hooks provided by the library to respond to UI and device orientation changes in functional components.
```javascript
function SomeComponent() {
useOrientationChange((o) => {
console.log("UI Orientation changed to:", o);
});
useDeviceOrientationChange((o) => {
console.log("Device Orientation changed to:", o);
});
}
```
--------------------------------
### Configure iOS AppDelegate.m for Orientation Locker
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Modifies the AppDelegate.m file for iOS projects (RN 0.76 and below) to include the Orientation.h import and implement the supportedInterfaceOrientationsForWindow method. This enables orientation locking functionality.
```objectivec
#import "Orientation.h"\n\n@implementation AppDelegate\n\n// ...\n\n- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {\n return [Orientation getOrientation];\n}\n\n@end
```
--------------------------------
### Implement onConfigurationChanged in MainActivity.java
Source: https://github.com/wonday/react-native-orientation-locker/blob/master/README.md
Adds the `onConfigurationChanged` method to `MainActivity.java` on Android. This method captures configuration changes, including orientation changes, and broadcasts them, allowing the orientation locker to react accordingly.
```java
// ...\n\nimport android.content.Intent;\nimport android.content.res.Configuration;\n\npublic class MainActivity extends ReactActivity {\n\n+ @Override\n+ public void onConfigurationChanged(Configuration newConfig) {\n+ super.onConfigurationChanged(newConfig);\n+ Intent intent = new Intent("onConfigurationChanged");\n+ intent.putExtra("newConfig", newConfig);\n+ this.sendBroadcast(intent);\n+ }\n\n // ......\n}
```
--------------------------------
### Configure iOS Orientation Settings
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Configures iOS-specific orientation options. Currently, it supports disabling face-up and face-down detection. This configuration should typically be done at application startup.
```javascript
import Orientation from 'react-native-orientation-locker';
import { Platform } from 'react-native';
// Configure at app startup
if (Platform.OS === 'ios') {
// Disable FACE-UP and FACE-DOWN orientation detection
Orientation.configure({
disableFaceUpDown: true
});
}
function App() {
return ;
}
```
--------------------------------
### Use Orientation Change Hook
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
A React hook that subscribes to UI orientation changes. It automatically handles listener cleanup and provides the current orientation to the callback function.
```javascript
import { useOrientationChange } from 'react-native-orientation-locker';
function AdaptiveScreen() {
const [columns, setColumns] = useState(2);
useOrientationChange((orientation) => {
if (orientation === 'LANDSCAPE-LEFT' || orientation === 'LANDSCAPE-RIGHT') {
setColumns(4);
} else {
setColumns(2);
}
});
return (
}
/>
);
}
```
--------------------------------
### Use Device Orientation Change Hook
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
A React hook that monitors physical device orientation changes. This is particularly useful for implementing motion-based interactions or gesture-based logic.
```javascript
import { useDeviceOrientationChange } from 'react-native-orientation-locker';
function ShakeToRefresh() {
const [devicePosition, setDevicePosition] = useState('PORTRAIT');
useDeviceOrientationChange((orientation) => {
setDevicePosition(orientation);
if (orientation === 'FACE-DOWN') {
muteNotifications();
}
});
return (
Device is currently: {devicePosition}
);
}
```
--------------------------------
### Add Device Orientation Listener
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Registers a callback for physical device orientation changes, which fires even when the screen is locked. This allows for detecting device orientation like 'FACE-DOWN', useful for specific device states.
```javascript
import Orientation from 'react-native-orientation-locker';
function MotionAwareComponent() {
const [deviceOrientation, setDeviceOrientation] = useState('UNKNOWN');
const [isFaceDown, setIsFaceDown] = useState(false);
useEffect(() => {
const onDeviceOrientationChange = (orientation) => {
console.log('Device moved to:', orientation);
setDeviceOrientation(orientation);
// Detect if phone is placed face-down (iOS/Windows)
if (orientation === 'FACE-DOWN') {
setIsFaceDown(true);
// Could trigger "do not disturb" mode
} else {
setIsFaceDown(false);
}
};
Orientation.addDeviceOrientationListener(onDeviceOrientationChange);
return () => {
Orientation.removeDeviceOrientationListener(onDeviceOrientationChange);
};
}, []);
return (
Device orientation: {deviceOrientation}
{isFaceDown && Phone is face down}
);
}
```
--------------------------------
### Check Auto-Rotate State (Android)
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Checks if the system auto-rotate setting is enabled on Android devices. This function is platform-specific and only available on Android. It takes a callback function that receives a boolean indicating the auto-rotate state.
```javascript
import Orientation from 'react-native-orientation-locker';
import { Platform } from 'react-native';
function AutoRotateChecker() {
const [autoRotateEnabled, setAutoRotateEnabled] = useState(null);
useEffect(() => {
if (Platform.OS === 'android') {
Orientation.getAutoRotateState((isEnabled) => {
console.log('Auto-rotate enabled:', isEnabled);
setAutoRotateEnabled(isEnabled);
if (!isEnabled) {
// Warn user that rotation won't work even after unlock
Alert.alert(
'Auto-Rotate Disabled',
'Enable auto-rotate in system settings for orientation changes to work.'
);
}
});
}
}, []);
return (
{Platform.OS === 'android'
? `Auto-rotate: ${autoRotateEnabled ? 'On' : 'Off'}`
: 'Auto-rotate check not available on this platform'}
);
}
```
--------------------------------
### Use Lock Listener Hook
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
A React hook that tracks changes to the orientation lock state. It triggers whenever the orientation is locked or unlocked via the library's API.
```javascript
import { useLockListener } from 'react-native-orientation-locker';
function LockIndicator() {
const [isLocked, setIsLocked] = useState(false);
const [lockedTo, setLockedTo] = useState(null);
useLockListener((orientation) => {
if (orientation === 'UNKNOWN') {
setIsLocked(false);
setLockedTo(null);
} else {
setIsLocked(true);
setLockedTo(orientation);
}
});
return (
{isLocked ? (
🔒 Locked to {lockedTo}
) : (
🔓 Orientation unlocked
)}
);
}
```
--------------------------------
### Lock Screen to Landscape Left Orientation
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Demonstrates locking the screen to a specific landscape orientation: landscape-left (camera on the left, home button on the right). This is useful for applications requiring a fixed landscape view, such as certain games. Orientation is reset on unmount.
```javascript
import Orientation from 'react-native-orientation-locker';
// Lock to specific landscape direction for gaming
function GameScreen() {
useEffect(() => {
// Camera left, home button right
Orientation.lockToLandscapeLeft();
return () => Orientation.unlockAllOrientations();
}, []);
return ;
}
```
--------------------------------
### Add UI Orientation Listener
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Registers a callback function that is invoked whenever the UI orientation changes. This listener does not fire when the orientation is locked. It requires a cleanup function to remove the listener upon component unmount.
```javascript
import Orientation from 'react-native-orientation-locker';
function ResponsiveLayout() {
const [orientation, setOrientation] = useState('PORTRAIT');
useEffect(() => {
const onOrientationChange = (newOrientation) => {
console.log('UI orientation changed to:', newOrientation);
setOrientation(newOrientation);
};
// Subscribe to UI orientation changes
Orientation.addOrientationListener(onOrientationChange);
// Cleanup on unmount
return () => {
Orientation.removeOrientationListener(onOrientationChange);
};
}, []);
return (
Current: {orientation}
);
}
```
--------------------------------
### Lock to All Orientations Except Upside Down (iOS)
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Demonstrates how to lock the orientation to allow all modes except portrait upside-down, which is the default behavior on most iOS apps. This is achieved using `Orientation.lockToAllOrientationsButUpsideDown()` and is platform-specific to iOS. The code resets orientation on unmount.
```javascript
import Orientation from 'react-native-orientation-locker';
import { Platform } from 'react-native';
function FlexibleOrientationScreen() {
useEffect(() => {
if (Platform.OS === 'ios') {
// Allow portrait, landscape-left, and landscape-right
// but not portrait upside-down
Orientation.lockToAllOrientationsButUpsideDown();
}
return () => Orientation.unlockAllOrientations();
}, []);
return Flexible content;
}
```
--------------------------------
### Add Orientation Lock Listener
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Registers a callback that is triggered when the orientation lock state changes. This occurs after calls to `lockToXXX` or `unlockAllOrientations`. The callback receives the new lock state, with 'UNKNOWN' indicating an unlocked state.
```javascript
import Orientation from 'react-native-orientation-locker';
function LockStateMonitor() {
const [lockState, setLockState] = useState('UNKNOWN');
useEffect(() => {
const onLockChange = (lockedOrientation) => {
console.log('Lock changed to:', lockedOrientation);
// lockedOrientation is 'UNKNOWN' when unlocked
setLockState(lockedOrientation);
};
Orientation.addLockListener(onLockChange);
return () => {
Orientation.removeLockListener(onLockChange);
};
}, []);
return (
{lockState === 'UNKNOWN'
? 'Orientation: Unlocked'
: `Locked to: ${lockState}`}
);
}
```
--------------------------------
### Unlock All Orientations in React Native
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Removes any orientation lock, allowing the screen to rotate freely based on device position and system settings. This function is part of the react-native-orientation-locker library and does not require any specific inputs.
```javascript
import Orientation from 'react-native-orientation-locker';
function SettingsScreen() {
const [isLocked, setIsLocked] = useState(true);
const toggleOrientationLock = () => {
if (isLocked) {
Orientation.unlockAllOrientations();
} else {
Orientation.lockToPortrait();
}
setIsLocked(!isLocked);
};
return (
Orientation: {isLocked ? 'Locked' : 'Unlocked'}
);
}
```
--------------------------------
### Remove All Orientation Listeners
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Removes all registered orientation, device orientation, and lock listeners simultaneously. This is essential for memory management and preventing leaks during component unmounting.
```javascript
import Orientation from 'react-native-orientation-locker';
function ScreenWithMultipleListeners() {
useEffect(() => {
Orientation.addOrientationListener((o) => console.log('UI:', o));
Orientation.addDeviceOrientationListener((o) => console.log('Device:', o));
Orientation.addLockListener((o) => console.log('Lock:', o));
return () => {
Orientation.removeAllListeners();
};
}, []);
return ;
}
```
--------------------------------
### Check if Orientation is Locked in React Native
Source: https://context7.com/wonday/react-native-orientation-locker/llms.txt
Synchronously checks if the screen orientation is currently locked by the react-native-orientation-locker library. It returns a boolean value: `true` if locked, and `false` otherwise. This is useful for determining the current state before performing orientation changes.
```javascript
import Orientation from 'react-native-orientation-locker';
function OrientationStatus() {
const [locked, setLocked] = useState(Orientation.isLocked());
const handleLockToggle = () => {
if (Orientation.isLocked()) {
Orientation.unlockAllOrientations();
} else {
Orientation.lockToPortrait();
}
// Update state after action
setLocked(Orientation.isLocked());
};
return (
Orientation locked: {locked ? 'Yes' : 'No'}
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.