React Native Navigation Drawer – Example using React Navigation V5

Navigation Drawer/Sidebar

This is an example of React Native Navigation Drawer for Android and IOS using React Navigation V5. We will use react-navigation to make a navigation drawer in this example. React Native Navigation Drawer is a very popular component in app development. It provides you to manage the number of app options in a very easy manner. A user can navigate from one screen to another screen very easily by just pulling out the drawer. Here is an example of a navigation drawer.

This example is updated for the React Navigation V5. For the React Navigation V4, you can scroll to the bottom.

To Create React Navigation Drawer

<NavigationContainer>
  <Drawer.Navigator
    drawerContentOptions={{
      activeTintColor: '#e91e63',
      itemStyle: { marginVertical: 5 },
    }}>
    <Drawer.Screen
      name="FirstPage"
      options={{ drawerLabel: 'First page Option' }}
      component={firstScreenStack} />
    <Drawer.Screen
      name="SecondPage"
      options={{ drawerLabel: 'Second page Option' }}
      component={secondScreenStack} />
  </Drawer.Navigator>
</NavigationContainer>

In this example, we will make a navigation drawer with Three screens. So let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

For React Native Navigation Drawer we need to add react-navigation and other supporting dependencies.

To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-navigation

npm install @react-navigation/native --save

2. Other supporting libraries react-native-gesture-handler, react-native-reanimated, react-native-screens and react-native-safe-area-context and @react-native-community/masked-view

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save

3. For the Drawer Navigator install

npm install @react-navigation/drawer --save

4. These steps are enough for the drawer navigation but in this example, we are also using between screens so we will also need Stack Navigator

npm install @react-navigation/stack --save

Note: When you use a navigator, you’ll need to follow the installation instructions of that navigator for any additional dependencies. If you’re getting an error “Unable to resolve module”, you need to install that module in your project.

You might get warnings related to peer dependencies after installation. They are usually caused by incorrect version ranges specified in some packages. You can safely ignore most warnings as long as your app builds.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install ios

To finalize the installation of react-native-gesture-handler, add the following at the top (make sure it’s at the top and there’s nothing else before it) of your entry files, such as index.js or App.js:

import 'react-native-gesture-handler';

Note: If you skip this step, your app may crash in production even if it works fine in development.

Project Structure

To start with this Example you need to create a directory named pages in your project and create three files FirstPage.js, SecondPage.js, and ThirdPage.js in it.

ReactNavigationStructure

Code for Navigation Drawer

App.js

Open App.js in any code editor and replace the code with the following code.

// React Native Navigation Drawer – Example using Latest Navigation Version //
// https://aboutreact.com/react-native-navigation-drawer //
import 'react-native-gesture-handler';

import * as React from 'react';
import { Button, View, Text, TouchableOpacity, Image } from 'react-native';

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

import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
import ThirdPage from './pages/ThirdPage';

const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();

const NavigationDrawerStructure = (props)=> {
  //Structure for the navigatin Drawer
  const toggleDrawer = () => {
    //Props to open/close the drawer
    props.navigationProps.toggleDrawer();
  };

  return (
    <View style={{ flexDirection: 'row' }}>
      <TouchableOpacity onPress={()=> toggleDrawer()}>
        {/*Donute Button Image */}
        <Image
          source={{uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/drawerWhite.png'}}
          style={{ width: 25, height: 25, marginLeft: 5 }}
        />
      </TouchableOpacity>
    </View>
  );
}

function firstScreenStack({ navigation }) {
  return (
      <Stack.Navigator initialRouteName="FirstPage">
        <Stack.Screen
          name="FirstPage"
          component={FirstPage}
          options={{
            title: 'First Page', //Set Header Title
            headerLeft: ()=> <NavigationDrawerStructure navigationProps={navigation} />,
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
  );
}

function secondScreenStack({ navigation }) {
  return (
    <Stack.Navigator
      initialRouteName="SecondPage"
      screenOptions={{
        headerLeft: ()=> <NavigationDrawerStructure navigationProps={navigation} />,
        headerStyle: {
          backgroundColor: '#f4511e', //Set Header color
        },
        headerTintColor: '#fff', //Set Header text color
        headerTitleStyle: {
          fontWeight: 'bold', //Set Header text style
        }
      }}>
      <Stack.Screen
        name="SecondPage"
        component={SecondPage}
        options={{
          title: 'Second Page', //Set Header Title
          
        }}/>
      <Stack.Screen
        name="ThirdPage"
        component={ThirdPage}
        options={{
          title: 'Third Page', //Set Header Title
        }}/>
    </Stack.Navigator>
  );
}

function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator
        drawerContentOptions={{
          activeTintColor: '#e91e63',
          itemStyle: { marginVertical: 5 },
        }}>
        <Drawer.Screen
          name="FirstPage"
          options={{ drawerLabel: 'First page Option' }}
          component={firstScreenStack} />
        <Drawer.Screen
          name="SecondPage"
          options={{ drawerLabel: 'Second page Option' }}
          component={secondScreenStack} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

export default App;

Open pages/Screen1.js in any code editor and the Replace the code with the following code.

Screen1.js

// React Native Navigation Drawer – Example using Latest Navigation Version //
// https://aboutreact.com/react-native-navigation-drawer //
import * as React from 'react';
import { Button, View, Text, SafeAreaView } from 'react-native';

const FirstPage = ({ navigation }) => {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 , padding: 16}}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 25,
              textAlign: 'center',
              marginBottom: 16
            }}>
            This is the First Page under First Page Option
          </Text>
          <Button
            onPress={() => navigation.navigate('SecondPage')}
            title="Go to Second Page"
          />
          <Button
            onPress={() => navigation.navigate('ThirdPage')}
            title="Go to Third Page"
          />
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          React Navigate Drawer
        </Text>
        <Text
          style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
}

export default FirstPage;

Screen2.js

Open pages/Screen2.js in any code editor and place the following code.

// React Native Navigation Drawer – Example using Latest Navigation Version //
// https://aboutreact.com/react-native-navigation-drawer //
import * as React from 'react';
import { Button, View, Text, SafeAreaView } from 'react-native';

const SecondPage = ({ navigation }) => {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, padding: 16 }}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 25,
              textAlign: 'center',
              marginBottom: 16
            }}>
            This is Second Page under Second Page Option
          </Text>
          <Button
            title="Go to First Page"
            onPress={() => navigation.navigate('FirstPage')}
          />
          <Button
            title="Go to Third Page"
            onPress={() => navigation.navigate('ThirdPage')}
          />
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          React Navigate Drawer
        </Text>
        <Text
          style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
}

export default SecondPage;

Screen3.js

Open pages/Screen3.js in any code editor and place the following code.

// React Native Navigation Drawer – Example using Latest Navigation Version //
// https://aboutreact.com/react-native-navigation-drawer //
import * as React from 'react';
import { Button, View, Text, SafeAreaView } from 'react-native';

const ThirdPage = ({ route, navigation }) => {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, padding: 16 }}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 25,
              textAlign: 'center',
              marginBottom: 16
            }}>
            This is Third Page under Second Page Option
          </Text>
          <Button
            onPress={() => navigation.navigate('FirstPage')}
            title="Go to First Page"
          />
          <Button
            onPress={() => navigation.navigate('SecondPage')}
            title="Go to Second Page"
          />
        </View>
        <Text style={{ fontSize: 18, textAlign: 'center', color: 'grey' }}>
          React Navigate Drawer
        </Text>
        <Text
          style={{ fontSize: 16, textAlign: 'center', color: 'grey' }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
}

export default ThirdPage;

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshot

NavigationDrawerScreenshot1   NavigationDrawerScreenshot2    NavigationDrawerScreenshot3     NavigationDrawerScreenshot4

Output in Online Emulator

So that was React Native Navigation Drawer – Example using React Navigation V5. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

I hope you liked it. 🙂

For React Navigation V4

If you are starting a new app or learning for the first time you should follow V5 steps to create React Navigation Drawer but if you are still developing the application using React Navigation V4 then you can follow the below steps.

Installation of Dependencies

Please run following commands in your project directory to install the dependencies

npm install react-navigation --save
npm install react-native-gesture-handler react-native-safe-area-context @react-native-community/masked-view react-native-screens react-native-reanimated --save
npm install react-navigation-drawer --save
npm install react-navigation-stack --save
cd ios && pod install && cd ..

Project Structure

Create the following project structure and copy the code

Here is the drawer.png if you want to download it

Code

App.js

//This is an example code for NavigationDrawer//
import React, { Component } from 'react';
//import react in our code.
import { View, Image, TouchableOpacity } from 'react-native';
// import all basic components

//Import React Navigation
import {createAppContainer} from 'react-navigation';
import {createDrawerNavigator} from 'react-navigation-drawer';
import {createStackNavigator} from 'react-navigation-stack';

//Import external files
import Screen1 from './pages/Screen1';
import Screen2 from './pages/Screen2';
import Screen3 from './pages/Screen3';

class NavigationDrawerStructure extends Component {
  //Structure for the navigatin Drawer
  toggleDrawer = () => {
    //Props to open/close the drawer
    this.props.navigationProps.toggleDrawer();
  };
  render() {
    return (
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
          {/*Donute Button Image */}
          <Image
            source={require('./image/drawer.png')}
            style={{ width: 25, height: 25, marginLeft: 5 }}
          />
        </TouchableOpacity>
      </View>
    );
  }
}

const FirstActivity_StackNavigator = createStackNavigator({
  //All the screen from the Screen1 will be indexed here
  First: {
    screen: Screen1,
    navigationOptions: ({ navigation }) => ({
      title: 'Demo Screen 1',
      headerLeft: ()=> <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: '#FF9800',
      },
      headerTintColor: '#fff',
    }),
  },
});

const Screen2_StackNavigator = createStackNavigator({
  //All the screen from the Screen2 will be indexed here
  Second: {
    screen: Screen2,
    navigationOptions: ({ navigation }) => ({
      title: 'Demo Screen 2',
      headerLeft: ()=> <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: '#FF9800',
      },
      headerTintColor: '#fff',
    }),
  },
});

const Screen3_StackNavigator = createStackNavigator({
  //All the screen from the Screen3 will be indexed here
  Third: {
    screen: Screen3,
    navigationOptions: ({ navigation }) => ({
      title: 'Demo Screen 3',
      headerLeft: ()=> <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: '#FF9800',
      },
      headerTintColor: '#fff',
    }),
  },
});

const DrawerNavigatorExample = createDrawerNavigator({
  //Drawer Optons and indexing
  Screen1: {
    //Title
    screen: FirstActivity_StackNavigator,
    navigationOptions: {
      drawerLabel: 'Demo Screen 1',
    },
  },
  Screen2: {
    //Title
    screen: Screen2_StackNavigator,
    navigationOptions: {
      drawerLabel: 'Demo Screen 2',
    },
  },
  Screen3: {
    //Title
    screen: Screen3_StackNavigator,
    navigationOptions: {
      drawerLabel: 'Demo Screen 3',
    },
  },
});

export default createAppContainer(DrawerNavigatorExample);

Screen1.js

//This is an example code for NavigationDrawer//
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Text } from 'react-native';
// import all basic components

export default class Screen1 extends Component {
  //Screen1 Component
  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 23 }}> Screen 1 </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    paddingTop: 20,
    alignItems: 'center',
    marginTop: 50,
    justifyContent: 'center',
  },
});

Screen2.js

//This is an example code for NavigationDrawer//
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Text } from 'react-native';
// import all basic components

export default class Screen2 extends Component {
  //Screen2 Component
  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 23 }}> Screen 2 </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    paddingTop: 20,
    alignItems: 'center',
    marginTop: 50,
    justifyContent: 'center',
  },
});

Screen3.js

//This is an example code for NavigationDrawer//
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Text } from 'react-native';
// import all basic components

export default class Screen3 extends Component {
  //Screen3 Component
  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 23 }}> Screen 3 </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    paddingTop: 20,
    alignItems: 'center',
    marginTop: 50,
    justifyContent: 'center',
  },
});

React Navigation V5 update brings lots of changes in terms of performance and structure. I will suggest you switch to V5 if you are on V4.


Related Posts

100 thoughts on “React Native Navigation Drawer – Example using React Navigation V5”

  1. Showing the error: undefined is not a function (evaluating ‘_this.props.navigationProps.toggleDrawer()’)
    toggleDrawer

    Can you please check this issue?

    Reply
  2. Hello, I have this issues when trying to pass params to another screen, e.g. passing email from users list to user detail screen….

    TypeError: TypeError: undefined is not an object (evaluating ‘this.props.navigation.state.params.JSON_ListView_Clicked_Item’)

    Reply
      • Actually I am. on the users list screen I have…..

        this.props.navigation.navigate(‘Profiles’, { Emailsss: item.email })} > {item.first_name} {item.last_name}

        and I get this error…

        TypeError: TypeError: undefined is not an object (evaluating ‘this.props.navigation.state.params.Emailsss’)

        I had to change from JSON_ListView_Clicked_Item to Emailsss to try fixing, but still not working.

        It Started happening since I implemented Drawer navigation.

        Reply
  3. Actually I am. on the users list screen I have…..

    this.props.navigation.navigate(‘Profiles’, { Emailsss: item.email })} > {item.first_name} {item.last_name}

    and I get this error…

    TypeError: TypeError: undefined is not an object (evaluating ‘this.props.navigation.state.params.Emailsss’)

    I had to change from JSON_ListView_Clicked_Item to Emailsss to try fixing, but still not working.

    Reply
  4. How can i remove the header from inside pages like
    Screen1 List -> Screen Details is page where i need back button how i can achieve this also change the header title.

    Reply
  5. I already update react native navigation into 3+ but i also get error : undefined is not and object : this.props.navigationProps.toggleDrawer. please help

    Reply
  6. null is not an object ( evaluating ‘RNGestureHandlerModule.Direction’)

    My app:
    “dependencies”: {
    “react”: “16.8.6”,
    “react-native”: “0.60.3”,
    “react-native-gesture-handler”: “^1.3.0”,
    “react-navigation”: “^3.11.1”
    }

    Reply
    • Hi Rod,
      Not yet as React Native versions are changing very frequently almost in a month so we think the code base will expire over a time but still We are planning for that with some solution of this frequent changes.

      Reply
  7. Thanks a lot, I was struggling to make it work. I was not sure if I had linked rn gesture handler correctly, but apparently I did. Just my code was not working but yours does so thanks a lot!

    Reply
  8. Thanks a lot excellent tutorial.I have a small doubt in my example i have created a custom drawer menu where top area will be occupied by main app icon and below will my drawer menu like home,about,settings… etc so my question is on press of the main icon i want to close the drawer menu and update the state of the home screen.

    Reply
  9. Hello Snehal,

    Thank you for the snippet.
    I tried to add multple indexes in a stackNavigator but there wasn’t any changes.
    Could you explain the utility to do that (if there is) and what should be the result.

    Reply
    • Hello Sevag, If you talk about the stack navigator then they are related to the single screen. In a single line, drawer navigation contains multiple stack navigator where each index of drawer navigator is a sidebar option and each index of the stack navigator is the multiple screens in the single option.
      If we have option1 with screen11, screen12, screen13, option2 with screen21, screen22, and option3 with screen31 then option1, option2, and option3 will be the drawer options and will come in drawer navigator but in the form of stack navigator with the same screen in a single option.

      Reply
  10. null is not an object ( evaluating ‘RNGestureHandlerModule.Direction’)

    App Dependencies

    “dependencies”: {
    “react”: “16.8.6”,
    “react-native”: “0.60.5”,
    “react-native-gesture-handler”: “^1.4.1”,
    “react-navigation”: “^3.12.0”
    },

    Reply
  11. Great tutorial!! You helped me a lot!! 🙂 I spend so much time to find out how to make proper navigation drawer, any tutorial was working but yours finally did the job 😀 Thank you so much.

    Reply
  12. Hi Snehal Agrawal,

    It’s very help to me to learn react native.
    I have a question how to close side menu when clicking outside of side menu part link other screen?
    it’s working when clicking on other screen on side menu but i need to close when open side menu then click out side of side menu want to close.

    Reply
  13. I swear to god i looked for around 12 hrs trying to do this and none of the blogs helped me like this one. A big thanks to whoever wrote this post . Keep coding

    Reply
  14. Hi Snehal,

    Two days i was hardly trying to configure am getting the error as toggle drawer is not a function.Am not getting toggleDrawer or openDrawer or closeDrawer in my navigation props.Anything i did wrong ?Please help me to solve this issue

    Reply
  15. I get blank white screen after do something in another screen in drawer orders and back to first screen in drawer products

    Reply
  16. error: bundling failed: Error: Unable to resolve module `@react-native-community/masked-view` from `node_modules\react-navigation-stack\lib\module\vendor\views\MaskedView.js`: @react-native-community/masked-view could not be found within the project.

    how to solve this sir?

    Reply