react native get navigation bar height

React Native - Get Navigation Bar Height

If you are building a React Native app and want to get the height of the navigation bar, there are a few ways to do it.

Method 1: Using "getHeaderMeasurements"

The easiest way is to use the "getHeaderMeasurements" method from the "react-navigation" library. This method returns an object that includes the height of the header as well as other measurements related to the header.


import { useHeaderHeight } from '@react-navigation/stack';

const headerHeight = useHeaderHeight();
  • The "useHeaderHeight" hook from the "react-navigation/stack" library returns the height of the header.

Method 2: Using "LayoutAnimation.measure"

Another way to get the navigation bar height is to use the "LayoutAnimation.measure" method. This method takes a ref to the navigation bar and returns its measurements.


import { LayoutAnimation, UIManager } from 'react-native';

UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);

const measureView = (ref) => new Promise((resolve) => {
  LayoutAnimation.measure(ref.current.getNode().getHandle(), (x, y, width, height, pageX, pageY) => {
    resolve(height);
  });
});

const headerHeight = await measureView(headerRef);
  • The "measureView" function uses "LayoutAnimation.measure" to get the height of the navigation bar.
  • The "headerRef" is a ref to the navigation bar.

Method 3: Using "onLayout" event listener

Finally, you can also use the "onLayout" event listener to get the height of the navigation bar. This method is a bit more manual, but it works.


import { useState } from 'react';

const [headerHeight, setHeaderHeight] = useState(0);

<View onLayout={(event) => setHeaderHeight(event.nativeEvent.layout.height)}>
  <Text>Hello World</Text>
</View>
  • The "onLayout" event listener is attached to a View that contains the navigation bar.
  • The event object passed to the "onLayout" function includes the height of the View.
  • The height is then stored in state using the "useState" hook.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe