Home > Mobile >  How do I reset my entire stack in React Native?
How do I reset my entire stack in React Native?

Time:07-23

My app consists of a Stack that looks like this:

  1. Home
  2. Start
  3. Task details
  4. End task

When the user presses a TouchableOpacity in the End task screen I want to reset the stack and return to the Home screen. I've tried using

navigation.dispatch(StackActions.popToTop());

But this isn't working. navigation is a variable assigned to useNavigation(). Is there a way to return to home using this hook?

CodePudding user response:

If Home is the initial route of the Stack, then we can reset the stack to the initial route using the popToTop function of the navigation object.

Furthermore, we do not need to use the useNavigation hook since EndTask is a screen located in the stack navigator. It will be passed to the component by the framework.

Here is a code snippet.

<TouchableOpacity onPress={() => navigation.popToTop()}> ... </TouchableOpacity>

CodePudding user response:

You can try,

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

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

CodePudding user response:

try this

props.navigation.reset({ routes: [{ name: "Mainpage" }] });
  • Related