Created
July 5, 2020 19:06
-
-
Save dminkovsky/c2cae19da21f70221f9f88a0b2efaa47 to your computer and use it in GitHub Desktop.
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 {useState, useEffect} from 'react'; | |
import type safeAreaInsets from 'safe-area-insets' | |
type SafeAreaInsetsModule = typeof safeAreaInsets | |
export type SafeAreaInsets = Pick<SafeAreaInsetsModule, 'top' | 'right' | 'bottom' | 'left'> | |
// Written like this because of https://stackoverflow.com/q/62726153/741970 | |
export default function useSafeAreaInsets() : SafeAreaInsets { | |
const [safeInsets, setSafeInsets] = useState({ | |
top: 0, | |
right: 0, | |
bottom: 0, | |
left: 0, | |
}); | |
useEffect(() => { | |
let safeAreaInsets : SafeAreaInsetsModule | undefined | |
function setSafeAreaInsets() { | |
// Get values from accessors: https://github.com/zhetengbiji/safeAreaInsets/blob/287ff9e20988c311dca3baf31fc49cb467e7ad47/src/index.ts#L187-L198 | |
const {top, right, bottom, left} = safeAreaInsets! | |
setSafeInsets({top, right, bottom, left}); | |
} | |
import('safe-area-insets').then(_safeAreaInsets => { | |
safeAreaInsets = _safeAreaInsets; | |
setSafeAreaInsets() | |
safeAreaInsets.onChange(setSafeAreaInsets); | |
}); | |
return () => safeAreaInsets?.offChange(setSafeAreaInsets) | |
}, []); | |
return safeInsets; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment