Dynamically Set Drawer/Sidebar Options in React Navigation Drawer

Dynamic React Navigation Drawer Options

In this post, I am going to share how to dynamically set drawer/sidebar options in React Navigation Drawer. We will use react-navigation to create a Navigation Drawer structure and going to use a custom navigation drawer instead of a default drawer.

This is very important topic when we want to control the visibility of the navigation drawer options according to the user authentication. There are also many other scenarios where you need to set the drawer options dynamically.

It is better to see React Native Navigation Drawer first if you are not aware of how to create a React Navigation Drawer and Custom Navigation Drawer / Sidebar with Image and Icon in Menu Options to create custom drawer.

Why do We Need to Set Drawer/Sidebar Options Dynamically?

As I already mentioned this is a very important example for many of the developers. There are many cases where you need to set the dynamic options in the sidebar, here are 3 to 4 cases which I want to share with you:

  1. Suppose your application has a user login as well as guest login for which you want to set the drawer options dynamically
  2. You have a multi-language application and you need to change the option labels in runtime
  3. You want to show the drawer navigation options on the basis of user permission
  4. If you have an E-Commerce application and you have listed categories in the sidebar you need to change the same on the basis of selection.

How to Set Drawer/Sidebar Options Dynamically?

If you create a basic navigation drawer you will get a default drawer coming from the left and will have the same options listed in the drawer which you have mentioned in your Drawer Navigator, but if you want to set the navigation drawer options dynamically then you need to create a custom drawer.
Drawer.Navigator provides a drawerContent prop to create your own custom drawer. Here is how you can create your own custom drawer.

const drawerStack = ({route}) => {
  return (
    <Drawer.Navigator
      drawerContentOptions={{
        activeTintColor: '#e91e63',
      }}
      drawerContent={(props) => {
        return (
          <DrawerContentScrollView {...props}>
            <DrawerItemList {...props} />
            {route.params.userType === 'user' ? (
              <DrawerItem
                label={({color}) => (
                  <Text style={{color}}>
                    Change Access to Guest
                  </Text>
                )}
                onPress={() =>
                  props.navigation.navigate(
                    'drawerStack',
                    {userType: 'guest'}
                  )
                }
              />
            ) : null}
          </DrawerContentScrollView>
        );
      }}>
      <Drawer.Screen
        name="FirstPage"
        options={{drawerLabel: 'First page Option'}}
        component={firstScreenStack}
        initialParams={{userType: route.params.userType}}
      />
      {route.params.userType === 'user' ? (
        <>
          <Drawer.Screen
            name="SecondPage"
            options={{drawerLabel: 'Second page Option'}}
            component={secondScreenStack}
          />
          <Drawer.Screen
            name="ThirdPage"
            options={{drawerLabel: 'Third page Option'}}
            component={thirdScreenStack}
          />
        </>
      ) : null}
    </Drawer.Navigator>
  );
};

Dynamic React Navigation Drawer Options Example Overview

In the example, we are going to create a landing screen that will have two buttons ‘User Login’ and ‘Guest Login’. On click of these buttons, the user/guest will navigate to the landing screen with some additions params. Once user/guest land on the landing screen we will show the navigation drawer option according to the params passed from landing screen.

I hope you understand what we are going to create, so without any delay let’s start with the example.

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. Now create FirstPage.js, SecondPage.js, ThirdPage.js, LandingPage.js in it.

DrawerDynamicValueStructure

Code for Dynamic React Navigation Drawer Options

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

App.js

// Dynamically Set Drawer/Sidebar Options in React Navigation Drawer
// https://aboutreact.com/dynamically-change-sidebar-options/

import 'react-native-gesture-handler';

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

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

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

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>
  );
};

const firstScreenStack = ({navigation, route}) => {
  return (
    <Stack.Navigator initialRouteName="FirstPage">
      <Stack.Screen
        name="FirstPage"
        component={FirstPage}
        initialParams={route.params}
        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>
  );
};

const 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.Navigator>
  );
};

const thirdScreenStack = ({navigation}) => {
  return (
    <Stack.Navigator
      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="ThirdPage"
        component={ThirdPage}
        options={{
          title: 'Third Page', //Set Header Title
        }}
      />
    </Stack.Navigator>
  );
};

const drawerStack = ({route}) => {
  return (
    <Drawer.Navigator
      drawerContentOptions={{
        activeTintColor: '#e91e63',
      }}
      drawerContent={(props) => {
        return (
          <DrawerContentScrollView {...props}>
            <DrawerItemList {...props} />
            {route.params.userType === 'user' ? (
              <DrawerItem
                label={({color}) => (
                  <Text style={{color}}>
                    Change Access to Guest
                  </Text>
                )}
                onPress={() =>
                  props.navigation.navigate(
                    'drawerStack',
                    {userType: 'guest'}
                  )
                }
              />
            ) : null}
          </DrawerContentScrollView>
        );
      }}>
      <Drawer.Screen
        name="FirstPage"
        options={{drawerLabel: 'First page Option'}}
        component={firstScreenStack}
        initialParams={{userType: route.params.userType}}
      />
      {route.params.userType === 'user' ? (
        <>
          <Drawer.Screen
            name="SecondPage"
            options={{drawerLabel: 'Second page Option'}}
            component={secondScreenStack}
          />
          <Drawer.Screen
            name="ThirdPage"
            options={{drawerLabel: 'Third page Option'}}
            component={thirdScreenStack}
          />
        </>
      ) : null}
    </Drawer.Navigator>
  );
};

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator screenOptions={{headerShown: false}}>
        <Stack.Screen name="LandingPage" component={LandingPage} />
        <Stack.Screen name="drawerStack" component={drawerStack} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

Open pages/FirstPage.js in any code editor and replace the code with the following code.

FirstPage.js

// Dynamically Set Drawer/Sidebar Options in React Navigation Drawer
// https://aboutreact.com/dynamically-change-sidebar-options/

import React, {useState} from 'react';
import {Button, View, Text, SafeAreaView} from 'react-native';

const FirstPage = ({navigation, route}) => {
  const [
    visible,
    setVisible
  ] = useState(route.params.userType === 'user');
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 18,
              textAlign: 'center',
              marginBottom: 16,
            }}>
            Dynamically Set Drawer/Sidebar Options
            {'\n'}
            in React Navigation Drawer
            {'\n\n'}
            First Page
          </Text>
          <Button
            onPress={() => navigation.navigate('LandingPage')}
            title="Go to Initial Page"
          />
          {visible ? (
            <Button
              onPress={() => {
                navigation.navigate(
                  'drawerStack',
                  {userType: 'guest'}
                );
                setVisible(false);
              }}
              title="Change Access to Guest"
            />
          ) : null}
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Dynamically Set Drawer/Sidebar Options
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default FirstPage;

Open pages/SecondPage.js in any code editor and replace the code with the following code.

SecondPage.js

// Dynamically Set Drawer/Sidebar Options in React Navigation Drawer
// https://aboutreact.com/dynamically-change-sidebar-options/

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: 18,
              textAlign: 'center',
              marginBottom: 16,
            }}>
            Dynamically Set Drawer/Sidebar Options
            {'\n'}
            in React Navigation Drawer
            {'\n\n'}
            Second Page
          </Text>
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Dynamically Set Drawer/Sidebar Options
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default SecondPage;

Open pages/ThirdPage.js in any code editor and replace the code with the following code.

ThirdPage.js

// Dynamically Set Drawer/Sidebar Options in React Navigation Drawer
// https://aboutreact.com/dynamically-change-sidebar-options/

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

const ThirdPage = ({navigation}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 18,
              textAlign: 'center',
              marginBottom: 16,
            }}>
            Dynamically Set Drawer/Sidebar Options
            {'\n'}
            in React Navigation Drawer
            {'\n\n'}
            Third Page
          </Text>
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Dynamically Set Drawer/Sidebar Options
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default ThirdPage;

Open pages/LandingPage.js in any code editor and replace the code with the following code.

LandingPage.js

// Dynamically Set Drawer/Sidebar Options in React Navigation Drawer
// https://aboutreact.com/dynamically-change-sidebar-options/

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

const LandingPage = ({navigation}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 18,
              textAlign: 'center',
              marginBottom: 16,
            }}>
            Dynamically Set Drawer/Sidebar Options
            {'\n'}
            in React Navigation Drawer
            {'\n\n'}
            Landing Page
          </Text>
          <Button
            onPress={() =>
              navigation.navigate('drawerStack', {userType: 'user'})
            }
            title="Go to Home as Registerd User"
          />
          <Text
            style={{
              textAlign: 'center',
              marginVertical: 16,
            }}>
            ------------- OR -------------
          </Text>
          <Button
            onPress={() =>
              navigation.navigate('drawerStack', {userType: 'guest'})
            }
            title="Go to Home as Guest"
          />
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Dynamically Set Drawer/Sidebar Options
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default LandingPage;

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 (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

DynamicallySetDrawerOptions1   DynamicallySetDrawerOptions2   DynamicallySetDrawerOptions3   DynamicallySetDrawerOptions4   DynamicallySetDrawerOptions5

This is how you can Dynamically set drawer/sidebar options in React Navigation Drawer. 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!

Hope you liked it. 🙂

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.