How to open drawer in react native using navigation.openDrawer()

1.8k Views Asked by At

I wanted to create a burger icon to open drawer but has been unable to do so. I have included the icon button on the right of my header. Whenever I click it to open the drawer, it shows the error of undefined function. I have mentioned the error below.

TypeError: navigation.openDrawer is not a function. (In 'navigation.openDrawer()', 'navigation.openDrawer' is undefined)

This is App.js, in this I have mentioned the code for drawer using createDrawerNavigator()

App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

import PassengerScreen from './Passenger';
import Lovedones from './Lovedones';
import NewTab from './FirstScreen';


import { createDrawerNavigator } from '@react-navigation/drawer';

const Drawer = createDrawerNavigator();

export default App=() => ( 
<NavigationContainer>
    <Drawer.Navigator initialRouteName="Passenger" drawerPosition="right" > 
        <Drawer.Screen name="Passenger" component={PassengerScreen} options= {{ title:'Passenger'}} />
        <Drawer.Screen name="Lovedones" component={Lovedones} options= {{ title:'loved ones!!'}} />
        <Drawer.Screen name="New Screen" component={NewTab}  />
      </Drawer.Navigator>
  </NavigationContainer>
);

This is AccountScreen.js, in this code, I have created the icon button to open the drawer using navigation.openDrawer()

AccountScreen.js

import * as React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { createStackNavigator } from '@react-navigation/stack';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { createDrawerNavigator } from '@react-navigation/drawer';


const Stack= createStackNavigator();

Account = () => {
  return <View style={styles.container}>
    <Text>Hello!!</Text>
  </View>
};
export default AccountStack =(navigation)=>(
          <Stack.Navigator >
            <Stack.Screen name="Account" component= {Account} options={{headerRight: () => (<Ionicons.Button name="reorder-three" color={"#FF0000"} size={40} backgroundColor= {"none"} onPress={() => navigation.openDrawer()}/> )  }} />
          </Stack.Navigator>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Kindly help me in identifying the error.

1

There are 1 best solutions below

0
On

The problem is in this line export default AccountStack =(navigation)=>.

Here your navigation variable points to the props instead of props.navigation.

To fix this you should destructure your navigation object from the props and change this line to

export default AccountStack =({navigation})=>