Created
September 20, 2021 02:45
-
-
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 */ ... }
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 {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