How to implement callBack function when screen change in react-native?

1.6k views Asked by At

I need a function when change screen executing, I mean when from screen home navigate to about screen executing the callback function.

Scenario

I want make global stack when change any naviagte run callback function for some check like (userToken, internet state, check location is one or off, etc.)

Try this

i create a class component for Stack-navigation and implemnet UNSAFE_componentWillUpdate, can detected any navigate.

Code

UNSAFE_componentWillUpdate(prevProp, prevState) {
    if (prevProp != this.props) {
      console.log('change state navigation');
    }
  }

Mistake this way

  • Can not detected first screen index-zero Home-screen.
  • I must write for each stack this code.

My Stack

<Stack.Navigator>
    <Stack.Screen
      name="Home"
      component={Home}
    />
   <Stack.Screen
      name="About"
      component={About}
    />
</Stack.Navigator>
2

There are 2 answers

3
Nooruddin Lakhani On

You can get the current route with "onNavigationStateChange" prop in "NavigationContainer"

React Navigation 4.x

onNavigationStateChange={(prevState, currentState) => {
    const currentScreen = this.getCurrentRouteName(currentState);
    const prevScreen = this.getCurrentRouteName(prevState);
}}

// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  // dive into nested navigators
  if (route.routes) {
    return getCurrentRouteName(route);
  }
  return route.routeName;
}

React Navigation 5.x

<NavigationContainer
      ref={navigationRef}
      onReady={() => routeNameRef.current = navigationRef.current.getCurrentRoute().name}
      onStateChange={() => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName = navigationRef.current.getCurrentRoute().name

        if (previousRouteName !== currentRouteName) {
          // The line below uses the expo-firebase-analytics tracker
          // https://docs.expo.io/versions/latest/sdk/firebase-analytics/
          // Change this line to use another Mobile analytics SDK
          Analytics.setCurrentScreen(currentRouteName);
        }

        // Save the current route name for later comparision
        routeNameRef.current = currentRouteName;
      }}
 >
   {/* ... */}
 </NavigationContainer>
0
aufamutawakkil On

for React Navigation 5.x

<NavigationContainer
  onStateChange={(st) => {
      let routeName = st.routes[st.index].name
      /* your other code */
  }}>
</NavigationContainer>