Skip to content

Instantly share code, notes, and snippets.

@dminkovsky
Created July 5, 2020 19:06
Show Gist options
  • Save dminkovsky/c2cae19da21f70221f9f88a0b2efaa47 to your computer and use it in GitHub Desktop.
Save dminkovsky/c2cae19da21f70221f9f88a0b2efaa47 to your computer and use it in GitHub Desktop.
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