Home > Mobile >  onPress function for DrawerNavigator
onPress function for DrawerNavigator

Time:12-15

I have created a DrawerNavigator in my react native app which looks like this. I just dont like the default header that react- native gives. So I wanna access it through an icon. I guess also using the onPress condition

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

// importing of all screens


const Drawer = createDrawerNavigator();

const DrawerContent = () => {
  return (
    <Drawer.Navigator>
      <Drawer.Screen
        name="Home"
        component={CategoryStack}
      />
      <Drawer.Screen name="Aboutus" component={Aboutus} />
      <Drawer.Screen name="Interest Recieved" component={InterestRecieved} />
   
    </Drawer.Navigator>
  );
};

const Stack = createStackNavigator();

const MainStack = () => {
  return (
    <Stack.Navigator>

      <Stack.Screen
        name="Loading"
        component={Loading}
        options={{ headerShown: false }}
      />
  
    </Stack.Navigator>
  );
};

export default MainStack;

How do I open it using an onPress of an icon? Thanks!

CodePudding user response:

React navigation useNavigation hook expose drawer actions - toggleDrawer,openDrawer and closeDrawer event handlers which you can use to open or close drawer.

import React from "react";
import { View, Text, StyleSheet, Pressable } from "react-native";
import { useNavigation } from "@react-navigation/native";

const ToggleDrawer = () => {
  const { toggleDrawer,closeDrawer,openDrawer } = useNavigation();

  return (
    <Pressable onPress={toggleDrawer}>{/** Add your Icon Here */}</Pressable>
  );
};


You can check in-depth drawer example

CodePudding user response:

In the header options you can customize the header and add for example an icon on the top left side like this.

useLayoutEffect(() => {
    navigation.setOptions({
        title: 'ScreenName',
        
        headerLeft: () => (
            <View style={{ marginLeft: 15 }}>
                <TouchableOpacity onPress={() => navigation.openDrawer()} >
                    {*INSERT ICON HERE*}
                </TouchableOpacity>
            </View>
        ),
    })

})
  • Related