'React Navigation: Is there a way to add another instance of a screen on top of an existing instance of that screen in StackNavigator?

In my React Native app, I have a stack navigator with screens A, B, and C. Screen A displays info on a given user. I want to create a switch user button on screen A that will load another instance of screen A, but displaying info for a different user. If I use this.props.navigation.navigate('A', {user: user2}) nothing happens because I'm already on screen A, ie. if you try to navigate to the same screen, it won't do it, even if the navigation params are different.

The reason I want to actually load a new instance of screen A rather than just staying on screen A and loading new user data is that when the user clicks change user, I want the visual effect that occurs when a new screen is added to the stack.

Does anyone know how I can approach this?



Solution 1:[1]

Use navigation.replace('A', {user: user2}); to replace the top of the stack. Here's an expo snack demonstrating: https://snack.expo.io/d7NkeEmcz

Solution 2:[2]

https://reactnavigation.org/docs/stack-actions/#push

You can also use StackActions for pushing new screen on top of current stack, as per documentation above example is:

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

const pushAction = StackActions.push('screenA', { user: user2 });

navigation.dispatch(pushAction);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 azundo
Solution 2 maXX