मुख्य कंटेंट तक स्किप करें

Drawer navigator

A common navigation pattern is to use the Drawer on the left (sometimes right) side to navigate between screens.

Before proceeding, first install @react-navigation/drawer:

npm install @react-navigation/drawer

A minimal example of Drawer based navigation

To use this Drawer, import it from @response-navigation/drawer: (swipe right to open)

import * as React from 'react'
import { Button, View } from 'react-native'
import { createDrawerNavigator } from '@react-navigation/drawer'
import { NavigationContainer } from '@react-navigation/native'

const HomeScreen = ({ navigation }) => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={() => navigation.navigate('Notifications')} title="Go to notifications" />
</View>
)

const NotificationsScreen = ({ navigation }) => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={() => navigation.goBack()} title="Go back home" />
</View>
)

const Drawer = createDrawerNavigator()

const App = () => (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Notifications" component={NotificationsScreen} />
</Drawer.Navigator>
</NavigationContainer>
)

export default App

Try this example on Snack

Opening and Closing Drawer

Use the following helpers to open and close Drawer:

navigation.openDrawer()
navigation.closeDrawer()

Try this example on Snack

If you want to switch Drawer, you call the following:

navigation.toggleDrawer()

Try this example on Snack

Each of these functions behind the scenes simply dispatches actions:

navigation.dispatch(DrawerActions.openDrawer())
navigation.dispatch(DrawerActions.closeDrawer())
navigation.dispatch(DrawerActions.toggleDrawer())

Try this example on Snack

If you want to determine if a drawer is open or closed, you can do the following:

import { useIsDrawerOpen } from '@react-navigation/drawer'

// ...

const isDrawerOpen = useIsDrawerOpen()

Done

To see how well you learned this lesson, take the test in our school's mobile app on this topic or in Telegram bot.

EnglishMoji!

React Navigation

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Dmitriy Vasilev

💲

EnglishMoji!