Last active
February 10, 2023 07:32
-
-
Save brayhoward/82ed6a68ed2c3727a67cd6e0863d6a1c to your computer and use it in GitHub Desktop.
A react hook for getting status bar height in ReactNative that works with iOS and android. This accounts for hotspot and GPS banners
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 { NativeModules, StatusBarIOS, Platform, StatusBar } from "react-native"; | |
import get from "lodash/get"; | |
const { StatusBarManager } = NativeModules; | |
export default function useStatusBarHeight() { | |
// Initialize w/ currentHeight b/c StatusBar.currentHeight works properly on android on Android | |
const [height, setHeight] = useState(StatusBar.currentHeight || 0); | |
useEffect(() => { | |
if (Platform.OS !== "ios") return; | |
StatusBarManager.getHeight(({ height }: { height: number }) => { | |
setHeight(height); | |
}); | |
const listener = StatusBarIOS.addListener( | |
"statusBarFrameWillChange", | |
(data: unknown) => { | |
setHeight(get(data, "statusBarData.frame.height", 0)); | |
} | |
); | |
return () => listener.remove(); | |
}, []); | |
return height; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've noticed that StatusBarIOS is deprecated and updated this hook to use NativeEventEmitter.
https://gist.github.com/ecklf/dc8dee4e1c9b8cd8011199416176fb3e
Thanks for putting me in the right direction!