React Native status bar event for dimensions in 0.62.x

Viewed 385

StatusBarIOS has a method addListener which allows us to listen for changes to the status bar height, like so:

StatusBarIOS.addListener('statusBarFrameWillChange', (statusBarData) => {
  this.setState({statusBarHeight: statusBarData.frame.height});
});

StatusBarIOS is deprecated, with a message that the code has been merged into StatusBar

enter image description here

How can we listen for the statusBarFrameWillChange event?

1 Answers

You can use the NativeEventEmitter module, here's an example of a react hook using the module to get the status bar height.

import React, { useState, useEffect } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';

const { StatusBarManager } = NativeModules;

export default function useStatusBarHeight() {
  const [value, setValue] = useState();

  useEffect(() => {
    const emitter = new NativeEventEmitter(StatusBarManager);
    StatusBarManager.getHeight((statusBarFrameData) => setValue(statusBarFrameData.height));
    const listener = emitter.addListener('statusBarFrameWillChange', (data) => setValue(data.frame.height));

    return () => listener.remove();
  }, []);

  return value;
}

This snippet also uses the StatusBarManager to grab the initial height.

Related