0

I'm looking for a way to call a function on each screen to track user interaction with each screen. so for example:

function track(screenName){
 console.log(screenName)
}

function ScreenA(){
 track('ScreenA')
 return <View />
}

function ScreenB(){
 track('ScreenB')
 return <View />
}

Instead of having to call the function manually in each screen separately , I believe there has to be a way to do it from the navigator directly. I'm using :

react-navigation 5.9 
react-native 0.65

2 Answers2

0

using @sushrut619 answer i applied the following :

export function App(){
  const [routeName, setRouteName] = React.useState('Unknown');

return (
   ...
   <NavigationContainer
     linking={linking}
     onStateChange={state => {
      const newRouteName = getActiveRouteName(state);

      if (routeName !== newRouteName) {
       setRouteName(newRouteName);
       //use whatever tracking function you want with newRouteName
      }
     }}>
     <MainAppStack />
    </NavigationContainer>
   ...
  );
}

and in a different utility file i added this function :

export function getActiveRouteName(state: NavigationState | PartialState<NavigationState> | undefined): string {
  if (!state || typeof state.index !== 'number') {
    return 'Unknown';
  }

  const route = state.routes[state.index];

  if (route.state) {
    return getActiveRouteName(route.state);
  }

  return route.name;
}

  • 1
    This approach has some issues and requires writing a utility manually, follow the official docs instead: https://reactnavigation.org/docs/screen-tracking/ – satya164 May 24 '22 at 11:55
  • 1
    For 5.x: https://reactnavigation.org/docs/5.x/screen-tracking – satya164 May 24 '22 at 12:11
0

The best answer for this is to implement the instructions in the latest version of react-navigation here

JackDev
  • 4,891
  • 1
  • 39
  • 48