Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation check if previous screen exists

I am looking desperately for a possibility to check if a previous screen exists in ReactNavigation.

Using this.props.navigation.goBack() returns false if no previous route exists, but I can not use it because if a previous route exists I get redirected.

Is there a possibility to check if I opened the app instead of navigated from another screen to the Home screen?

Thank you. I am not using Redux. It would make such stuff easier but I would like to avoid using it at the moment.

like image 890
Juko Avatar asked Feb 16 '18 15:02

Juko


People also ask

How do you check the previous screen in React Native?

If you want to find out previous route/screen name from navigation stack in react native app so you can use this function. How to use? previousRouteName(props. navigation);

How do I go back in react navigation?

The header bar will automatically show a back button, but you can programmatically go back by calling navigation. goBack() . On Android, the hardware back button just works as expected. You can go back to an existing screen in the stack with navigation.


Video Answer


3 Answers

As of React Navigation 5 you can use useNavigationState hook inside functional component this way:

const routesLength = useNavigationState(state => state.routes.length);
console.log('routesLength', routesLength);

If routesLength > 1 then it is not the first screen in stack

Or you can use navigation.canGoBack()

like image 175
copperfox Avatar answered Oct 03 '22 05:10

copperfox


There is an easier way:

if(this.props.navigation.isFirstRouteInParent()) {
    //a previous screen does not exist
} else {
    //a previous screen does exist
}
like image 33
nwales Avatar answered Oct 03 '22 05:10

nwales


What could be a solution (not sure that it's the best one) would be to spend in the param object the previous screen. With that, if the params exists would mean that a previous screen exists.

For example:

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',

  params: { previous_screen: 'CURRENT_SCREEN' },

  action: NavigationActions.navigate({ routeName: 'NEXT_SCREEN' }),
});

this.props.navigation.dispatch(navigateAction);

And then in the next screen:

const { navigation } = this.props;
if (navigation.state.params && navigation.state.params.previous_screen) {
  // A previous screen exists
} else {
  // No previous screen
}
like image 41
Théo dvn Avatar answered Oct 03 '22 04:10

Théo dvn