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
.
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;
As can be seen above, we have provided three props for the Drawer:
Line 17: The ref
assigned to the drawer
ref we created earlier allows us to programmatically open/close the drawer using our drawer
ref.
Lines 21–23: The width of our drawer is denoted by drawerWidth
while renderNavigationView
renders the component we supply to it in the drawer. Here, we have supplied our custom Drawer
component.
Line 29: We use the drawer
ref to invoke the openDrawer
function to open the drawer after the button is clicked. To programmatically close the drawer, we can also use the closeDrawer
function in a similar way.