React native clear Stack Navigator stack

Paras Watts picture Paras Watts · Sep 21, 2017 · Viewed 26.2k times · Source

I have few screens which I navigate through one by one. Screen1->screen2-screen3->screen4-Home

What I want is when I go to home then the previous history of navigation should be cleared and back pressing back button should not go to last navigated screen which is screen 4. Currently When I press back button on home screen it takes me back to the last route in the stack which is screen4. I have used below code. It is giving me error no route defined or key Home. Which I have already defined in Screens class. Any help would be appreciated.

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

onPress={() =>  this.props.navigation.dispatch(resetAction)}

Answer

Rajesh Nasit picture Rajesh Nasit · Jul 19, 2020

in V5, you can use

this.props.navigation.reset({
              index: 0,
              routes: [{name: 'Home'}],
            });

Using hooks

import {useNavigation} from '@react-navigation/native';

const navigation = useNavigation();

navigation.reset({
        index: 0,
        routes: [{name: 'Events'}],
      });