Last active
December 4, 2019 19:05
-
-
Save joncardasis/e9cf5124b9fc44bf39d9ece126412adf to your computer and use it in GitHub Desktop.
Simple React Native rotation lock with React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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; | |
} | |
}; | |
}, []); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useLockOrientationPortrait } from './hooks'; | |
function App() { | |
useLockOrientationPortrait(); // Lock app to portrait by default | |
render ( | |
... | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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