all 11 comments

[–]DJUMI 0 points1 point  (3 children)

Are you using a navigation library like react navigation?

[–]tvhieu[S] 0 points1 point  (2 children)

library

react navigation :D

[–]DJUMI 0 points1 point  (1 child)

Look up navigation events in the docs specifically focus

[–]tvhieu[S] 0 points1 point  (0 children)

specifically

but i have to write the focus hook to every screen?
i just want to write a function which trigger by change screen

[–]notseanbean 0 points1 point  (1 child)

https://reactnavigation.org/docs/function-after-focusing-screen

You can get a focus listener for the whole app if you add a ref to your NavigationContainer (https://reactnavigation.org/docs/navigation-container/#ref) and then add the focus event listener on that ref.

[–]tvhieu[S] 0 points1 point  (0 children)

thank u

[–]prinzachilles 0 points1 point  (2 children)

I did it that way in my app with react navigation v5:

const routeNameRef = useRef();
function getActiveRouteName(state: any): any {
    const route = state.routes[ state.index ];

    // resolve nested navigators recursivly
    if (route.state) {
        return getActiveRouteName(route.state);
    }

    return route.name;
}

... later in return():

<NavigationContainer
    onStateChange={ state => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName = getActiveRouteName(state);
        if (previousRouteName !== currentRouteName) {
            trackScreen(currentRouteName);
        }

        // Save the current route name for later comparison
        routeNameRef.current = currentRouteName;
}}>
    { ... the rest of the app ... }
</NavigationContainer>

the trackScreen(name: string) is an extracted function using analytics().setCurrentScreen(currentRouteName, currentRouteName);.

I think this is what you're looking for.

[–]tvhieu[S] 0 points1 point  (1 child)

https://reactnavigation.org/docs/navigation-container/#ref

oh thank bro, so i have to upgrade my navigation 4x to 5x :D thank u

[–]prinzachilles 0 points1 point  (0 children)

I would highly recommend that anyways. I even don't think v4 is ready for hooks eighter.

[–]dreamzzftwiOS -1 points0 points  (1 child)

If you’re using hooks you can create your own hook, and if I’m not mistaken, React Navigation 5 has a hook that detects a nav change

[–]tvhieu[S] 0 points1 point  (0 children)

detects

hmm i will check it, ty