3

I'm using ex-navigation with Exponent and React Native. I have a multi-tab TabNavigation, where each tab has its own StackNavigation element inside. When the user changes tabs in the TabNavigation, I'd like to reset the stack of the previous tab.

I can already reset the StackNavigation element using popToTop, but my issue is determining when the user changes tabs. Is there an emitted tab-change event, or route change event, that I can subscribe to?

Travis G.
  • 218
  • 2
  • 9

1 Answers1

1

After some help from the ex-navigation developers, I have found a way to clear the tab stack upon navigating away. We can attach an onPress handler to the TabNavigation component, and it will be passed the default event handler. After calling the default handler to change tabs, we can perform any other desired actions. Here's a version of a TabNavigation that clears the stack of the first tab when the user clicks any of the tabs:

export default class RootNavigation extends React.Component {
  constructor(props) {
    super(props);
    this.onPress = this.onPress.bind(this);
  }

  onPress(switchTab) {
    switchTab();
    requestIdleCallback(() => {
      this.props.navigation.performAction(({stacks}) => {
        stacks("first").popToTop();
      });
    });
  }

  render() {
    return (
      <View>
        <TabNavigation initialTab="first">
          <TabNavigationItem id="first-tab" onPress={this.onPress}>
            <StackNavigation id="first" navigatorUID="first" initialRoute="first-route" />
          </TabNavigationItem>

          <TabNavigationItem id="second-tab" onPress={this.onPress}>
            <StackNavigation id="second" navigatorUID="second" initialRoute="second-route" />
          </TabNavigationItem>

          <TabNavigationItem id="third-tab" onPress={this.onPress}>
            <StackNavigation id="third" navigatorUID="third" initialRoute="third-route" />
          </TabNavigationItem>
        </TabNavigation>
      </View>
    );
  }
};

Note that the stack we manipulate through stacks("first") must have both an id and navigatorUID set to "first".

Travis G.
  • 218
  • 2
  • 9