Arnaud
Arnaud

Reputation: 5122

How to reset the state of a StackNavigator nested in a DrawerNavigatior?

I am building an app whose navigation is based on a DrawerNavigator from the react-navigation library.

This navigator has 3 tabs:

The StackNavigator consists of one screen that lets the user search for an item, and a second screen where the user sees the search results.

I do not want the search results page to be a tab of a DrawerNavigator, this is why I implemented this structure.

The problem is: if the user has already performed a search, when he clicks on the "Search" tab, he does not come back to the search screen but to the search results screen. I would prefer that the user comes back to the search screen.

How can I achieve that?

Upvotes: 8

Views: 1250

Answers (3)

ND verma
ND verma

Reputation: 297

work for me

const resetStackNavigator = (navigation, routeName) => {
          const resetAction = CommonActions.reset({
            index: 0, // Reset to the initial route (first screen)
            routes: [
              {
                name: routeName, 
              },
            ],
          });
        
          navigation.dispatch(resetAction);
        };
    
    
    
    import React from 'react';
    import { View, Text, Button } from 'react-native';
    
    const myScreen = ({ navigation }) => {
      return (
        <View>
          <Text>This is a stack screen </Text>
          <Button
            title="Reset StackNavigator"
           onPress={() => resetStackNavigator(navigation, '_ScreenNameToResetTo_')}
          />
        </View>
      );
    };
    
    export default myScreen;

Upvotes: 0

You can achive this using navigation dispatch with navigationActions

import { NavigationActions } from 'react-navigation';

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({
      routeName: 'DrawerScreen',
      params: {},
      action: NavigationActions.navigate({ routeName: 'SearchScreen' }),
    }),
  ],
})
navigation.dispatch(resetAction)

Upvotes: 2

Masood
Masood

Reputation: 1594

import { NavigationActions } from 'react-navigation';

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
      NavigationActions.navigate({ routeName: 'SearchScreen'})
  ]
})

Here in your button or any element with event add this: this.props.navigation.dispatch(resetAction)

<Button
    onPress= {
        () => this.props.navigation.dispatch(resetAction)
    }
    title='Back to Search'
/>

Upvotes: 1

Related Questions