VK1
VK1

Reputation: 1716

How do I conditionally render a header in a Stack Navigator for React Native Navigation?

I would like my initial page to NOT contain a header. However, I would like a header to appear on each subsequent page. Right now my current stackNavigator looks like this:

const AppNavigator = createStackNavigator(
  {
    HomeScreen: HomePage,
    SecondPage: SecondPage,
    Account: Account,
    About: About,
  },
  {
    initialRouteName: 'HomeScreen',
    headerMode: 'none',
    navigationOptions: {
      headerVisible: false,
    },
  },
);

export default createAppContainer(AppNavigator);

Here is the basic boilerplate for my second page:

const SecondPage: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <View style={styles.body}>
        <View style={styles.sectionContainer}>
          <Text style={styles.sectionTitle}>This is the Secondpage</Text>
        </View>
      </View>
    </>
  );
};

export default SecondPage;

Upvotes: 0

Views: 1035

Answers (2)

Auticcat
Auticcat

Reputation: 4489

You have three ways of doing this using navigationOptions:

1) Directly when you define your navigator:

createStackNavigator({
   {
      HomeScreen: {
      screen : HomePage,
      navigationOptions: {header : null}
   },
      SecondPage: SecondPage,
      Account: Account,
      About: About,
  },

  { ... }   //your navigationOptions

})

2) Directly inside the screen as said by Shashank Malviya. Only if you aren't using a functional component.

3) Return defaultNavigationOptions as a function and use navigation state:

createStackNavigator({
  { ... }, //your RouteConfigs

  {
     initialRouteName: 'HomeScreen',
     headerMode: 'none',
     defaultNavigationOptions : ({navigation}) => navigation.state.routeName === "HomePage" && {header: null}
  },

})

Upvotes: 2

Shashank Malviya
Shashank Malviya

Reputation: 765

Can be written on every component before render

 static navigationOptions = ({ navigation }) => {
        const { state } = navigation
        return {
          headerVisible: true // can be true or false
        }
      }

Upvotes: 0

Related Questions