Skip to content

Instantly share code, notes, and snippets.

@brayhoward
Last active February 10, 2023 07:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brayhoward/82ed6a68ed2c3727a67cd6e0863d6a1c to your computer and use it in GitHub Desktop.
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
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;
}
@ecklf
Copy link

ecklf commented Aug 3, 2021

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment