React Native applications often use two or more navigators at once. At first, I had a problem with the combination of stack navigator and drawer navigator, fortunately I combined them in way, that they work properly and now I can share this knowledge.
Let’s start from the beginning, which is App.js component. In our case, it will be very simple, because it returns only one component, which is DrawerNavigator.
App.js
import React, {Component} from 'react';
import DrawerNavigator from './components/DrawerNavigator';
export default class App extends Component {
render() {
return (
<DrawerNavigator />
);
}
}
In the drawer navigator we create four screens – one main, which contains StackNavigator and three others, which contains other data.
DrawerNavigator.js
import React, {Component} from 'react';
import { createDrawerNavigator, createAppContainer } from 'react-navigation';
import Screen1 from './Screen1';
import Screen2 from './Screen2';
import Screen3 from './Screen3';
import ContentComponent from './ContentComponent';
import {Dimensions} from 'react-native';
import StackNavigator from './StackNavigator';
const MyDrawerNavigator = createDrawerNavigator({
Home: {screen: StackNavigator},
Screen1: {screen: Screen1},
Screen2: {screen: Screen2},
Screen3: {screen: Screen3},
},
{
initialRouteName: 'Home',
drawerWidth: Dimensions.get('window').width,
drawerPosition: 'left',
}
);
const AppContainer = createAppContainer(MyDrawerNavigator);
export default class DrawerNavigator extends Component {
render() {
return <AppContainer />;
}
}
As you can see as the main screen (initialRouteName) in the drawer navigator we set StackNavigator, so let’s deal with this component
Here case is a bit different: as the main screen we set HomeScreen and from its level (specifically from the header) we want to open the drawer navigator. However, the navigation property in the stack navigator does not have the option to open drawer navigator. That’s why we need to pass this option from drawer navigator to stack navigator, and from it to the HomeScreen main component. We will do this by passing it with screenProps – as an additional property.
Now in the HomeScreen component we can read the property opening the drawer navigator and place it in the header using static navigationOptions.
I write code that (usually) works. I tame WordPress, learn React, explore the world of DevOps, and click around in the Linux console. I optimize code as a hobby, because laziness is the purest form of productivity. I do my best not to lose my mind somewhere between a bug and a deadline.