TLDR: I have a Login screen where user logs in and navigates to second screen. There I want to open the menu and have the user name appear as text. How can I pass the user name to the menu? (DrawerNavigator).
Some samples of my code below.
Router:
import MyMenu from './MyMenu';
const MyStack = StackNavigator({
Login: {screen: Login},
Home: {screen: Home}
// more screens...
});
export const MyDrawer = DrawerNavigator({
Main: { screen: MyStack }
},
{ contentComponent: MyMenu }
);
Home Screen:
openMenu() {
this.props.navigation.navigate('DrawerOpen', userName);
}
MyMenu:
render() {
const userName = this.props.navigation.state.params;
return (
<View>
<Text>{userName}</Text>
// more stuff
</View>
);
}
I think this is what you want.
import MyMenu from './MyMenu';
const MyStack = StackNavigator({
Login: {screen: Login},
Home: {screen: Home}
// more screens...
});
export const MyDrawer = DrawerNavigator({
Main: { screen:({navigation}) => <MyStack screenProps={drawerNavigation:navigation}/> }
},
{ contentComponent: MyMenu }
);
Then you can access drawer's navigation from your Stack navigation like below.
this.props.screenProps.drawerNavigation.DO_WHATEVER
You need to pass props to your MyMenu Component:
Router:
export const MyDrawer = DrawerNavigator({
Main: { screen: MyStack }
},
{ contentComponent: (props) => <MyMenu {...props} /> }
);
Home Screen:
openMenu() {
this.props.navigation.navigate('DrawerOpen', {userName: userName});
}
Alright, after spending so much time on this, I finally found a solution.
Simply put, you can only send navigation props when navigating to a new screen - 'DrawerOpen' does not count for this.
To solve this I had to change my structure a little bit, instead of having the DrawerNavigator as the root drawer, I have a StackNavigator as the root drawer.
Before:
const MyStack = StackNavigator({
Login: {screen: Login},
Home: {screen: Home}
// more screens...
});
export const MyDrawer = DrawerNavigator({
Main: { screen: MyStack }
},
{ contentComponent: MyMenu }
);
After:
const MyStack = StackNavigator({
Home: {screen: Home},
// more screens...
});
const MyDrawer = DrawerNavigator({
Main: { screen: MyStack }
},
{ contentComponent: MyMenu }
);
export const RootStack = StackNavigator({
Login: {screen: Login},
Drawer: {
screen: MyDrawer,
navigationOptions: { header: null } } //prevent double header
});
Now in Login screen I navigate to Drawer like this:
_login() {
this.props.navigation.navigate('Drawer', { userName: userName });
}
And finally in MyMenu (which is part of 'Drawer'):
render() {
const { userName } = this.props.navigation.state.params;
return (
<View>
<Text>{userName}</Text>
// more stuff
</View>
);
}
It works!