'Set Header Height with Safe Area Insets with React Navigation
I can pass screenOptions
to the Navigator with
a headerStyle
object with a height
property, but I'd like the height to take into account the SafeAreaInsets
and not be a fixed value
There's getDefaultHeaderHeight
function that takes into account the statusBarHeight
here https://github.com/react-navigation/react-navigation/blob/dbe961ba5bb243e8da4d889c3c7dd6ed1de287c4/packages/drawer/src/views/Header.tsx#L8 - is there a way I can call this function and simply add n
pixels across all devices?
Solution 1:[1]
I'm not sure about in React Navigation 5, but height
is not a supported property of headerStyle
in React Navigation 6. The rest of this response is based on references to and my personal experience with React Navigation 6.
You may need to write a fully custom header component to achieve what you want. React Navigation even has a Guide on supporting safe areas. Summarizing the Guide from React Navigation, plus a little extra real-world usage of it, you can then use the useSafeAreaInsets
hook from react-native-safe-area-context
and then in the style for the View
surrounding your custom header, you can use the top
value from the hook response as paddingTop
to ensure that your header avoids the status bar area. If the rest of the height of your header needs to be explicitly defined, you'll need to add that top
value to your height number as the height
property of this View
. If the height of your header is dynamic and based on its content, you probably don't actually need to set an explicit height on your header.
Example:
import React, { useEffect } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
const MyComponent = () => {
const insets = useSafeAreaInsets();
const navigation = useNavigation();
useEffect(() => {
navigation.setOptions({
// only us height if you REALLY need it, height should be dynamic based on content
header: () => <View style={{ paddingTop: insets.Top, height: value + insets.Top }}>
{content of your custom header}
</View>
});
}, [insets, navigation]);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Emily |