skip to Main Content

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?

3

Answers


  1. 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>
    
    Login or Signup to reply.
  2. You can try,

    import {CommonActions} from '@react-navigation/native';
    
    navigation.dispatch(
              CommonActions.reset({
                    index: 0,
                    routes: [
                     {
                       name: 'Home'
                     },
                    ],
              })
    );
    
    Login or Signup to reply.
  3. try this

    props.navigation.reset({ routes: [{ name: "Mainpage" }] });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search