Home > Software engineering >  get the active route name from within a screen
get the active route name from within a screen

Time:01-05

I created a stack navigator and I am trying to do UI changes based on the current screen route name, however, props.navigation.state doesn't get updated when navigating to another screen , I am accessing it inside home screen:

useEffect(() => {
  console.log(navigation.state.routeName)
},[navigation])

note I am using react navigation version 4.4.1

CodePudding user response:

Hard to answer without more context on where you're calling your useEffect, but you can try to add a focus listener as referenced in the react navigation 4.x documentation (https://reactnavigation.org/docs/4.x/function-after-focusing-screen/)

useEffect(() => {
 const focusListener = navigation.addListener('didFocus', () => {
   console.log(navigation.state.routeName)
 });

 return () => focusListener.remove()
},[navigation])

CodePudding user response:

let try this

import {createAppContainer} from 'react-navigation';

const getRootNavigation = () => createAppContainer(YourNavigator());

 render() {
    const RootNavigator = getRootNavigation();
    return (
      <View style={styles.container}>
        <RootNavigator
          onNavigationStateChange={(prev, next) =>
            onNavigationStateChange(prev, next)
          }
        />
      </View>
    );
  }


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;
}

function onNavigationStateChange(prevState, currentState) {
    const currentScreen = getCurrentRouteName(currentState);
  
  }
}

then save your currentScreen by mobx or redux

then you can get current screen name anywhere.

  •  Tags:  
  • Related