React Native not passing data through navigation param

Viewed 274

I'm trying to pass some data when navigating to another screen, but it's not working. It navigates to the screen but the data is undefined.

I have this button on the 'Produto' Screen:

onPress={() => {
  props.navigation.navigate("Login", {
    test: "This is just a test"
  });
}}

Login Screen:

const LoginScreen = props => {    
  const test = props.navigation.getParam("test");
  console.log(test);

test is undefined.

My Navigator (I removed imports and other stuff from this snippet):

const MainNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    Produto: ProdutoScreen,
  },
  {
    initialRouteName: "Home"
  }
);

const LoginNavigator = createStackNavigator(
  {
    Login: LoginScreen
  }
);

const DrawerNavigator = createDrawerNavigator(
  {
    Main: {
      screen: MainNavigator
    },
    Login: {
      screen: LoginNavigator
    }
  }
);

const SwitchNavigator = createSwitchNavigator({
  Start: StartScreen,
  Home: DrawerNavigator
});
2 Answers

Just update the line where you are trying to access the param. Like this,

const LoginScreen = props => {    
  const test = props.navigation.state.params.test;
  console.log(test);
}

Just do this

const MainNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    Produto: ProdutoScreen,
    Login: LoginScreen,     //this will resolve your issue
  },
  {
    initialRouteName: "Home"
  }
);
Related