React Navigation : How to prevent navigation to unmounted tab screen with Material Bottom Tab Navigator when Icon is pressed?

Viewed 469

I have a question for React Native developers here. I use createMaterialBottomTabNavigator, and I wanted one button in the tab bar to open a screen not in a tab, but in a stack navigator instead. According to the documentation, we can prevent default behaviour with a useEffect hook in the target screen and do our navigation from there. So here is my code in the target screen :

useEffect(() => {
    const unsubscribe = navigation.addListener("tabPress", (e) => {
      // Prevent default behavior of tab press in bottom navigator
      e.preventDefault();
      // Open screen in stack navigator, not in tab navigator
      navigation.navigate("TargetScreen");
    });
    return unsubscribe;
  }, [navigation]);

It works well, except for one detail: Material Bottom Tab Navigator doesn’t mount its routes before they are first focused, so the first time I press the button it opens the screen in a tab. After that, when I press the same button, it opens the screen in a stack navigator as expected.

Does anyone know a workaround for that issue? Is there a way to force Material tab to mount routes before they are focused? Or a way to call a hook when the screen first mounts?

Thanks!

0 Answers
Related