React Navigation: Navigate Back To Root using NavigationActions.reset, goBack and getStateForAction

Turnipdabeets picture Turnipdabeets · May 12, 2017 · Viewed 20.5k times · Source

Say I've navigated through 4 screens in my StackNavigator App and now I want to go back to the first screen. There seems to be three different ways to do this and they do navigate to where I want to do, however each way has an animation that cycles through each previous screen.

Is there a clean way to navigate from SCREEN_D to SCREEN_A?

In other words, I don't want to see SCREEN_C and SCREEN_B a split of a second before seeing SCREEN_A when navigating backwards from SCREEN_D

navigation.navigate(SCREEN_A);
...
navigation.navigate(SCREEN_B);
...
navigation.navigate(SCREEN_C);
...
navigation.navigate(SCREEN_D);

Three ways to do this:

1.

return this.props.navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [NavigationActions.navigate({ routeName: 'SCREEN_A'})]
                  }));

2.

 const {SCREEN_B_KEY} = this.props.navigation.state.params
 this.props.navigation.goBack(SCREEN_B_KEY)

3.

const defaultGetStateForAction = Navigation.router.getStateForAction;

Navigation.router.getStateForAction = (action, state) =>{
  if(action.type === "Navigation/BACK"){
    const routes = [
      {routeName: 'First'},
    ];
    return {
      ...state,
      routes,
      index: 0,
    };
  }
  return defaultGetStateForAction (action,state);
}

Answer

Sultan Ali picture Sultan Ali · Apr 11, 2019

react-native navigation has popToTop we can use it like blow

this.props.navigation.popToTop()