Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate to parent of parent stack

I have this scenario where i have a StackNavigator nested in a TabNavigator nested in another StackNavigator.

const TabOneStack = StackNavigator({
  ScreenA: { screen: ScreenA },
  ScreenB: { screen: ScreenB }
});

const MainTabs = TabNavigator({
  TabOne: { screen: TabOneStack },
  TabTwo: { screen: TabTwoStack }
});

const Root = StackNavigator({
  HomeScreen: { screen: HomeScreen },
  MainTabs: { screen: MainTabs }
});

Everything works but i cant figure out how to navigate for example from ScreenA back to the Home screen in the root StackNavigator. After the HomeScreen the User navigates directly to ScreenA. The back button in the header in ScreenA works fine and brings me back to Home but need a way to have a button that brings me back to the HomeScreen. this.props.navigation.goBack() does not work unfortunately.

i also tried

const backAction = NavigationActions.reset({
  index: 0,
  key: null,
  actions: [
    NavigationActions.navigate({ routeName: 'HomeScreen'})
  ]
});    
this.props.navigation.dispatch(backAction));

but i get:

There is no route defined for key HomeScreen. Must be one of: 'ScreenA', 'ScreenB'.

What is the correct way to do this?

like image 703
aschmid00 Avatar asked Mar 08 '23 11:03

aschmid00


1 Answers

To traverse from child StackNavigator back to parent StackNavigator, do:

class ScreenA extends Component {
    render() {
        return (<Button onPress={() => {
            this.props.navigation.dispatch({type: 'Navigation/BACK'});
        }} title='ScreenA. back to Home' />);
    }
}

this.props.navigation.dispatch() with 'Navigation/BACK' works exactly the same as the top-most back button.
It differs from goBack() by apply parent-child stack traversing, while goBack() does not.

Result:

enter image description here

And note @Jigar's answer is also correct, it's just a shorthand notation of mine. The key is to pass null argument into goBack(). It won't work without that.

this.props.navigation.goBack(null);
like image 54
Val Avatar answered Apr 11 '23 02:04

Val