Wes
Wes

Reputation: 1945

React Native Elements: How do I display header component in navigation bar?

I'm trying to display the header component in the navigation header but it's being displayed outside of it. The bar in blue is supposed to replace the white rectangular space at the top.

 render() {
    return (
      <View>
        <View
          style={{
            paddingTop: Constants.statusBarHeight
          }}
        >
          <Header leftComponent={{ text: "Delete Account" }} />
        </View>
        <ScrollView
          style={{ marginTop: 20 }}
          keyboardShouldPersistTaps="always"
        >
          <View
            style={{
              flex: 1,
              alignItems: "center",
              justifyContent: "center"
            }}
          >
          ...
          </View>
        </ScrollView>
      </View>
    );
  }

enter image description here

Upvotes: 0

Views: 5931

Answers (3)

6rchid
6rchid

Reputation: 1301

The proper way to do this in React Navigation v6 and in addition to disabling the default header from React Navigation (as doubles mentioned) is to have the navigation header property return the Header component, all under useLayoutEffect . Like this:

  useLayoutEffect(() => {
    navigation.setOptions({
      header: () => (
        <Header
          leftComponent={...}
          centerComponent={...}
          rightComponent={...}
        />
      ),
    });
  }, [navigation]);

This will create a custom header for that screen component, of course, you can set the header property in the parent/stack level too.

Upvotes: 0

Junius L
Junius L

Reputation: 16142

You are adding marginTop to the view that contains the header, which moves the header 50 margins down, remov marginTop from the view

<View>
  <Header leftComponent={{ text: 'Delete Account' }} />
</View>

You also need to use centerComponent with placement property to move the title to the left, and hide header in your stackNavigator

class AccountScreen extends React.Component {
  render() {
    return (
      <View style={{ marginTop: Constants.statusBarHeight }}>
        <Header placement="left" centerComponent={{ text: 'Delete Account' }} />
        <Text>Account Screen</Text>
      </View>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Account: {
      screen: AccountScreen,
      navigationOptions: {
        header: null,
      },
    },
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Account',
  }
);

enter image description here

DEMO

Upvotes: 3

doubles
doubles

Reputation: 71

If you want to create your own header bar (React native elements), you have to hide the header from React navigation stack totally from app setup or hide it on specific screen Hide header in stack navigator React navigation

Upvotes: 1

Related Questions