React Native clear the previous screen from the navigation stack

26,920

Solution 1

When Login or Register is completed successfully you have to reset your navigation stack like below,

import { StackActions, NavigationActions } from 'react-navigation';
const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName: 'Events' })],
});
this.props.navigation.dispatch(resetAction)

and additionally in your Event page you have to add one static method if you don't want header there.

static navigationOptions = navigation => ({
        header: null
});

Hope it will help you.

Solution 2

In Version V5 onwards

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

Using hook in functional componant,

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

const navigation = useNavigation();

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

Solution 3

2021 update:

Here's a much easier solution:

this.props.navigation.replace("Events");

This will replace the current screen with a new one while keeping any previous screens in the navigation stack.

Food for thought

Ideally you'd use best practices and do something like:

import * as ROUTES from "../routes/constants"

this.props.navigation.replace(ROUTES.EVENTS);

where routes/constants.js,

const EVENTS = "Events";
...

export {
    EVENTS,
    ...
};

Solution 4

In V5.x we have reset method

navigation.reset({
  index: 0,
  routes: [{ name: 'ScreenName' }],
});
Share:
26,920
Wai Yan Hein
Author by

Wai Yan Hein

What up?

Updated on July 09, 2022

Comments

  • Wai Yan Hein
    Wai Yan Hein almost 2 years

    I am developing a React native application for learning purposes. I am now implementing navigation using React Navigation. I am using stack navigation. But I cannot find a way to remove the previous screen from navigation history and kill the app.

    I set up my navigation like this.

    const AppStack = createStackNavigator({
      Login: {
        screen: Login
      },
      Register: {
        screen: Register
      },
      Events: {
        screen: Events
      }
    });
    

    As you can see in the above code, I open the log in screen by default. After login, I open the Events screen like this.

    this.props.navigation.navigate('Events');
    

    The problem is that, When I am on the events page, I can see the back button in the navigation bar. When I press on it, I was brought back to the sign in page.

    But what I want is that, after login, I want to remove the sign-in page from the stack. When I am on the events page, when I click on the back button, the app should be closed. Maybe it might not have the back button. It will just act like a first screen in that case. How can I do that?