How to open drawer navigator from header of stack navigator?


Passing drawer navigator to the stack navigator header is pretty easy, though it might seem difficult. It is seen by the number of questions asked on programming portals. Therefore, I will present here a shortened version of the code that will show how to achieve this effect.

In drawer nawigator we set stack nawigator as main screen (Home)

DrawerNavigator.js

const MyDrawerNavigator = createDrawerNavigator({
    Home: {screen: StackNavigator},
    ...
},
{
    initialRouteName: 'Home',
    contentComponent: ContentComponent,
    drawerWidth: Dimensions.get('window').width,
    drawerPosition: 'left',
    drawerBackgroundColor: 'transparent',
}
);

const AppContainer = createAppContainer(MyDrawerNavigator);

export default class DrawerNavigator extends Component {
    render() {
        return <AppContainer />;
    }
}

Do stack nawigatora przekazujemy opcję otwarcia drawer navigatora w postaci screenProps.

In screenProps we pass open drawer nawigator function to stack navigator

StackNavigator.js

const AppContainer = createAppContainer(MyStackNavigator);

export default class StackNavigator extends Component {
  render() {
    return <AppContainer screenProps={{ openDraw: () => this.props.navigation.dispatch(DrawerActions.openDrawer()) }} />;
  }
}

Then, in the main screen of the navigator, we read screenProps and assign open drawer navigator option to created button .

HomeScreen.js

static navigationOptions = ({ screenProps }) => ({
      title: 'Home',
      headerLeft: (
          <Button onPress={() => screenProps.openDraw() }
              title="OPEN"
              color="red"
          />
      ),
})

Efect:

How to open drawer navigator from header of stack navigator? // Jak otworzyć drawer nawigator z nagłówka stack nawigatora?

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *