John doe
John doe

Reputation: 3870

How to navigate to directly to the initial route when using TabNavigator?

I am using TabNavigator from react-navigation. It's working fine but I need to do a little trick.

When I navigate between StackNavigator routes, after changing tabs I need my route go directly in the initial route. So I need the route state to be reset.

const HomeStack = StackNavigator({
  Main: { screen: HomeScreen },
  Profile: { screen: ProfileScreen },


});

const AboutStack = StackNavigator({
  Main: { screen: AboutScreen },
});

TabNavigator(
  {
    Home: { screen: HomeStack },
    About: { screen: AboutStack },
  }

Let's say I am in the Main route from the Home tab and then I have navigated to Profile before switching to the About tab. When I go back to the Home tab I want my app directly to navigate to the Main route and clear history. Just like a reset.

Any suggestion ?

Upvotes: 1

Views: 1146

Answers (1)

Théo dvn
Théo dvn

Reputation: 940

You maybe could use the willFocus listener in the Profile route of your HomeStack.

Listener:

class Profile extends Component {
  componentDidMount() {
    this.didFocusListener = this.props.navigation.addListener(
      'didFocus',
      () => { console.log('did focus') },
    );
  }

  componentWillUnmount() {
    this.didFocusListener.remove();
  }

  render() {
    return ( /* your render */ );
  }
}

And then in the case you are on Main and you are navigating to your Profile route. You should set a params in the navigation to say that the previous route is Main.

Route parameters: navigation.navigate('Profile', { previous_screen: 'Main' });

So now in your willFocus listener:

  • if the previous_screen param is set, it means that you don"t have to do anything.
  • If not, means that you come from the other tab and that it will navigate to the wrong route. So you can either reset you're navigation route or just navigate to the 'Profile' route.

NOTE:

I didn't try this solution and maybe the transition animation is not going to be smooth. So tell me if it does the job well or not.

Upvotes: 1

Related Questions