1

I'm using reaxt-navigation 6 in a react-native 0.68 project:

    "@react-navigation/bottom-tabs": "6.3.1",
    "@react-navigation/drawer": "6.4.1",
    "@react-navigation/native": "6.0.10",
    "@react-navigation/stack": "6.2.1",

We can listen to "screen scoped" events from inside a screen quite easily with props.navigation.addEventListener from inside a screen.

Is there a way to listen "globally" for any screen event with only one addEventListener call (from outside any screen) ?

Żabojad
  • 2,946
  • 2
  • 32
  • 39

1 Answers1

1

This is quite a poor way of writing it but should give you an idea if you are in a bind like I was, as it isn't immediately obvious.

You need to use the onStateChange prop on your NavigationContainer as such. The following will work for up to a two-level nested navigator and return the name as a string for example, "Main-Sub". You can extend this logic as far as your navigation containers are nested.

onStateChange={(state) => {
  const route = state?.routes[state?.index];
  const subRouteIndex = route?.state?.index;
  let subRoute;
  if (subRouteIndex !== undefined) {
    subRoute = route?.state?.routes[subRouteIndex];
  }

  // name = "MainName-SubName"
  const name = subRoute?.name ? `${route.name}-${subRoute.name}` : route.name;
}
user37309
  • 597
  • 5
  • 14