Search code examples
javascriptreactjsreact-nativereact-navigationreact-navigation-stack

React Navigation 6 - Custom header height


I have a custom header component:

function CustomHeader() {
    return (
       <View style={{ height: headerHeight }}>
          {/* Some buttons in a row... */}
          <View 
            style={{ 
              position: "absolute",
              alignSelf: "center",
              top: headerHeight/2
            }} 
          />
       </View>
    )
}

As you can see, I am absolutely positioning a view in the center of my header, with a top of headerHeight/2.

For getting headers height I am doing:

 import { useHeaderHeight } from "@react-navigation/elements";

 const headerHeight = useHeaderHeight();

But... it returns me 0, as in my stack navigator I am doing:

 screenOptions={{
    headerShown: false,
 }}

because, I am rendering the custom header inside the Screen.

How can I solve this problem? I need to get the default headers height used in Stack Navigators in order to stylize my component.


Solution

  • The useHeaderHeight hook is for getting the height of a header that's rendered by React Navigation.

    If you just want to get the default header height, then you need to use getDefaultHeaderHeight:

    import { getDefaultHeaderHeight } from '@react-navigation/elements';
    import { useSafeAreaFrame, useSafeAreaInsets } from 'react-native-safe-area-context';
    
    // ...
    
    const MyComponent = () => {
      const frame = useSafeAreaFrame();
      const insets = useSafeAreaInsets();
    
      const headerHeight = getDefaultHeaderHeight(frame, false, insets.top);
    
      // ...
    
    }