Butri
Butri

Reputation: 457

How to Unmount a screen when moving to another in React Native

I'm developing a React Native app using React Navigation v4, React Hooks and ES6.

I have 2 bottom tabs (Movies, Shows) and 4 screens with the following Stack structure:

**Movies**
 -- MovieList
 -- MovieDetail

**Shows**
 -- ShowList
 -- ShowDetail

My scenario

1) Moving from Movie list to an individual movie page

MovieList contains a list of movies, when I click on one of them, I first fetch some API data then move to the MovieDetail screen like this

dispatch(apiFetchActions.fetchMovies(movieId)).then((response) => {      
      props.navigation.navigate({
        routeName: "MovieDetail",
        params: {
          assetId: movieId,
          assetName: movieTitle,
        },
      });

MovieDetail is now on top of the Movies stack and MovieList at the bottom

2) Moving to a different tab (navigation stack)

I then click on Shows (2nd Tab) which takes me to the ShowList using props.navigation.navigate('ShowList')

3) The problem

If I click on the Movies Tab, I expect to be moved back to MovieList but since MovieDetail was never unmounted, it is still at the top of the Movies stack meaning that I see an old screen. I have to click twice to go back to the MovieList screen.

I've read quite a few suggestions on how to use onFocus/onBlur subscription however I could not found a solution using React Hooks.

My ideal solution would be to find a way to listen to the onBlur status in MovieDetail screen possibly using useEffect hook and somehow unmount it before leaving.

Upvotes: 4

Views: 982

Answers (1)

Butri
Butri

Reputation: 457

I found a way to make it easier to always move to the initial top of the stack when you click on any bottom tab icons.

You simply need to add the on Press and the screen reference like this

Stars: {
    screen: StarsNavigator,
    navigationOptions: ({ navigation }) => ({
      tabBarIcon: (tabInfo) => {
        return (
          <Ionicons name="ios-people" size={22} color={tabInfo.tintColor} />
        );
      },
      tabBarLabel: Platform.OS === "android" ? <Text>Stars</Text> : "Stars",
      tabBarOnPress: () => {
        navigation.navigate("StarsList");
      },
    }),
  },

Star is one of my screens in BottomTabNavigator and using navigation.navigate("You Screen") does the trick. So regardless in which level of the stack you find yourself, every time you click on the Star tab you always end up to the original top level.

Upvotes: 1

Related Questions