Drawer Navigator
A drawer navigator adds a slide-out panel — typically from the left edge of the screen. Users open it by swiping from the edge or tapping a hamburger menu button. It's a common pattern for apps with many top-level sections that don't all fit in a tab bar.
Setup
The drawer navigator requires react-native-gesture-handler and react-native-reanimated, which we installed in the setup lesson. Import and create the navigator:
import { createDrawerNavigator } from '@react-navigation/drawer';
const Drawer = createDrawerNavigator();
Basic Drawer
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { View, Text, StyleSheet } from 'react-native';
const Drawer = createDrawerNavigator();
function HomeScreen() {
return (
<View style={styles.container}>
<Text style={styles.title}>Home</Text>
</View>
);
}
function SettingsScreen() {
return (
<View style={styles.container}>
<Text style={styles.title}>Settings</Text>
</View>
);
}
function AboutScreen() {
return (
<View style={styles.container}>
<Text style={styles.title}>About</Text>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, alignItems: 'center', justifyContent: 'center' },
title: { fontSize: 24 },
});
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Settings" component={SettingsScreen} />
<Drawer.Screen name="About" component={AboutScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
Each Drawer.Screen appears as an item in the drawer panel. The navigator automatically adds a hamburger menu icon to the header. Swipe from the left edge or tap the icon to open the drawer.
Adding Icons
Add icons to drawer items with drawerIcon in screenOptions:
import { Ionicons } from '@expo/vector-icons';
<Drawer.Navigator
screenOptions={({ route }) => ({
drawerIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === 'Home') iconName = 'home-outline';
else if (route.name === 'Settings') iconName = 'settings-outline';
else if (route.name === 'About') iconName = 'information-circle-outline';
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
>
Opening and Closing Programmatically
Use navigation.openDrawer(), navigation.closeDrawer(), and navigation.toggleDrawer() from any screen:
function HomeScreen({ navigation }) {
return (
<View style={styles.container}>
<Button title="Open Drawer" onPress={() => navigation.openDrawer()} />
</View>
);
}
Drawer Position
By default the drawer slides from the left. To open from the right:
<Drawer.Navigator screenOptions={{ drawerPosition: 'right' }}>
The defaults are functional, but most apps need a custom drawer — a user avatar, styled items, a logout button. That's what we'll build next.