J. Hesters
J. Hesters

Reputation: 14806

React Navigation (V2 / V3): How to access navigation.state.index in navigationOptions on screen

I'm building a React Native app and for my navigation I use React Navigation (V3). For my UI elements I use React Native Elements.

I have a screen which I reuse in multiple navigators. Sometimes it is at the root of a stack, and sometimes it's pushed on with a stack. I want to programmatically add a headerLeft element to this screen navigationOptions based on its position in the stack, because I either want the default back button to show, or a burger menu icon to show, if the screen is at the root of the stack (because the stack is nested in a drawer).

So I tried the following:

export class ScannerScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerLeft:
      navigation.state.index > 0 ? (
        undefined 
      ) : (
        <Icon type="ionicon" name="ios-menu" onPress={navigation.toggleDrawer} />
      ),
    title: strings.scannerTitle
  });
// ...

The problem is this doesn't work as navigation.state.index is undefined here. How would one do this with React navigation?

Edit: As per request I added a screenshot of console.log(navigation) (via <Icon />s onPress.) enter image description here

Upvotes: 1

Views: 604

Answers (1)

J. Hesters
J. Hesters

Reputation: 14806

I found a hacky solution, which is okay but I also dislike it a bit:

const stackConfig: StackNavigatorConfig = {
  cardStyle: styles.card,
  navigationOptions: {
    headerBackTitleStyle: styles.headerBackTitle,
    headerStyle: styles.header,
    headerTintColor: "black"
  }
};

const HomeStack = createStackNavigator(
  { HomeScreen, RestaurantDetailScreen, MenuScreen, ScannerScreen },
  {
    ...stackConfig,
    initialRouteName: "HomeScreen",
    navigationOptions: ({ navigation }) => ({
      headerLeft:
        parseFloat(navigation.state.key.slice(-1)) > 1 ? (
          undefined
        ) : (
          <Icon
            containerStyle={styles.leftIcon}
            type="ionicon"
            name={getIconName("menu")}
            onPress={navigation.toggleDrawer}
          />
        ),
      ...stackConfig.navigationOptions
    })
  }
);

This way it automatically sets it for the whole stack. You can also do this in the respective screen individual navigation options. But this only works, since the automatically assigned key for the screen contains it's index.

Upvotes: 1

Related Questions