Skip to content
Advertisement

How to get previous route name from React Navigation

I am trying to get previous route name to my current screen. Because based on the previous screen name, I have to show/hide few objects in current screen.

To get previous screen name, I have tried following

componentDidMount() {
    const { navigation } = this.props;
    if (navigation.state.params && navigation.state.params.previous_screen) {
       console.log('navigation.state.params.previous_screen', navigation.state.params.previous_screen);
    }
}

But, It’s getting undefined in console log.

Any suggestions?

Advertisement

Answer

You need to use NavigationActions

goToScreen = () => {

  const navigateAction = NavigationActions.navigate({
    routeName: 'Profile',

    params: { previous_screen: 'Home' }, // current screen

    action: NavigationActions.navigate({ routeName: 'Profile' }), // screen you want to navigate to
  });

  this.props.navigation.dispatch(navigateAction);
  
};

call the above function in your onPress

<Text onPress={this.goToScreen}>Go to screen</Text>

In your other screen

componentDidMount = () => {
  
  const { navigation } = this.props;
  if (navigation.state.params && navigation.state.params.previous_screen) {

    this.setState({
      previous_screen: navigation.state.params.previous_screen
    });

  } else {
    console.log("ERROR");
  }
};

Working demo

Function version

const goToScreen = () => {
  // assuming that navigation is passed in props
  props.navigation.navigate('Settings', {
    previous_screen: 'Home'
  })
}

And access the params like

const Settings = ({ route }) => {
  const { previous_screen } = route.params;

  return ....
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement