Skip to content

Instantly share code, notes, and snippets.

@joncardasis
Last active December 4, 2019 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joncardasis/e9cf5124b9fc44bf39d9ece126412adf to your computer and use it in GitHub Desktop.
Save joncardasis/e9cf5124b9fc44bf39d9ece126412adf to your computer and use it in GitHub Desktop.
Simple React Native rotation lock with React Hooks
/**
1. Install and configure `react-native-orientation-locker`.
2. In both the iOS and Android projects, set the allowed platform orientations to everything except upside down.
*/
import { useEffect } from 'react';
import Orientation, { OrientationType } from 'react-native-orientation-locker';
export function useLockOrientationPortrait() {
Orientation.lockToPortrait();
}
/// Unlocks rotation when a component mounts. Resets orientation when component unmounts.
export function useAnyOrientation() {
useEffect(() => {
let previousOrientation: OrientationType;
Orientation.getOrientation(orientation => {
previousOrientation = orientation;
Orientation.unlockAllOrientations();
});
return () => {
switch (previousOrientation) {
case 'LANDSCAPE-LEFT':
Orientation.lockToLandscapeLeft();
break;
case 'LANDSCAPE-RIGHT':
Orientation.lockToLandscapeRight();
break;
default:
Orientation.lockToPortrait();
break;
}
};
}, []);
}
import { useLockOrientationPortrait } from './hooks';
function App() {
useLockOrientationPortrait(); // Lock app to portrait by default
render (
...
);
}
import { useAnyOrientation } from '../hooks';
function PhotoGallery() {
useAnyOrientation(); // Allow any platform supported orientation while this component is rendered
return (
<View>
...
</View>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment