What is Drawer Navigation in React Native?
Drawer Navigation
In React Native, Drawer Navigation is a navigation pattern that allows you to create a side menu that slides in and out from the left or right side of the screen. It's commonly used in Android mobile apps to provide easy access to a list of screens or actions.
Although there are libraries for creating drawers in iOS, React Native officially supports drawers in Android.
To add a drawer in React Native, we need to wrap the DrawerLayoutAndroid component around our main content view. Then, we supply the component we want to display in the drawer in the renderNavigationView prop of DrawerLayoutAndroid.
Example
An example is given below.
import React, { useRef } from "react";import {DrawerLayoutAndroid,Text,StyleSheet,View,Button,} from "react-native";const Drawer = () => (<View style={styles.container}><Text>Drawer content</Text></View>);const DrawerApp = () => {const drawer = useRef(null);return (<DrawerLayoutAndroidref={drawer}drawerWidth={300}renderNavigationView={Drawer}><View style={styles.container}><Text style={{marginBottom: 12}}>Main Content</Text><Buttontitle="Open drawer"onPress={() => drawer.current.openDrawer()}/></View></DrawerLayoutAndroid>);};const styles = StyleSheet.create({container: {flex: 1,alignItems: "center",justifyContent: "center",padding: 16,},});export default DrawerApp;
Explanation
As can be seen above, we have provided three props for the Drawer:
Line 17: The
refassigned to thedrawerref we created earlier allows us to programmatically open/close the drawer using ourdrawerref.Lines 21β23: The width of our drawer is denoted by
drawerWidthwhilerenderNavigationViewrenders the component we supply to it in the drawer. Here, we have supplied our customDrawercomponent.Line 29: We use the
drawerref to invoke theopenDrawerfunction to open the drawer after the button is clicked. To programmatically close the drawer, we can also use thecloseDrawerfunction in a similar way.