Skip to content

Instantly share code, notes, and snippets.

@MAgungHKM
Created September 20, 2021 02:45
Show Gist options
  • Save MAgungHKM/3c7c3607f9862964c281b52ccf4de0ee to your computer and use it in GitHub Desktop.
Save MAgungHKM/3c7c3607f9862964c281b52ccf4de0ee to your computer and use it in GitHub Desktop.
React Native Device Orientation hook. (example: const deviceOrientation = useOrientation(); if (deviceOrientation === 'PORTRAIT') {...} else {/* LANDSCAPE */ ... }
import {isUndefined} from 'lodash';
import {useEffect, useState, useCallback} from 'react';
import {Dimensions, ScaledSize} from 'react-native';
const dimensions = Dimensions.get('window');
export type Orientation = 'LANDSCAPE' | 'PORTRAIT';
const getOrientation = ({
width,
height,
}: {
width: number,
height: number,
}): Orientation => (width <= height ? 'PORTRAIT' : 'LANDSCAPE');
export function useOrientation(): Orientation {
const [orientation, setOrientation] = useState(getOrientation(dimensions));
const onChange = useCallback(({window: scr}: {window: ScaledSize}) => {
setOrientation(getOrientation(scr));
}, []);
useEffect(() => {
let mounted = true;
let subscription;
if (mounted) subscription = Dimensions.addEventListener('change', onChange);
return () => {
mounted = false;
if (!isUndefined(subscription)) subscription.remove();
};
}, [onChange]);
return orientation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment