How to Hide Navigation Option from Navigation Drawer / Sidebar

Introduction

This post is about How to Hide Navigation Option from Navigation Drawer / Sidebar in React Native. We will use react-navigation to make a navigation drawer in this example. I hope you have already seen our last post on React Native Navigation Drawer because in this post we are just extending the last post to hide the navigation option from the Navigation Drawer.

Hide navigation drawer option means while creating navigation drawer we have a screen in our navigation drawer which should be visible in the navigation option in the left menu but with some changes, we can also control the visibility of the option.

This option is very useful when you have to manage the visibility of the options on the basis of authority / access, For example if you have to different navigation options on the basis of user is logged in or not.

In this example, we will have a navigation drawer with 4 screens but only 2 navigation options available in the drawer menu. On the first screen, we will have two buttons to open two hidden screen which are the part of the navigation drawer but not in navigation drawer menu.

To Hide the Navigation Option from the Navigation Drawer

To hide the navigation option from the navigation drawer we will use drawerContent prop of Drawer.Navigator. This prop provides independence to replace default navigation drawer with our custom one. We have added some custom code to customise the navigation drawer.

The logic is simple we have just taken all the routes passed in drawer navigator and filtered out all those which we don’t want on drawer navigation. We have used DrawerContentScrollView and DrawerItemList to create the drawer option.

<Drawer.Navigator
  drawerContentOptions={{
    activeTintColor: '#e91e63',
    itemStyle: {padding: 0},
  }}
  drawerContent={(props) => {
    const filteredProps = {
      ...props,
      state: {
        ...props.state,
        routeNames: props.state.routeNames.filter(
          // To hide single option
          // (routeName) => routeName !== 'HiddenPage1',
          // To hide multiple options you can add & condition
          (routeName) => {
            routeName !== 'HiddenPage1'
            && routeName !== 'HiddenPage2';
          },
        ),
        routes: props.state.routes.filter(
          (route) =>{
            route.name !== 'HiddenPage1'
            && route.name !== 'HiddenPage2',
          },
        ),
      },
    };
    return (
      <DrawerContentScrollView {...filteredProps}>
        <DrawerItemList {...filteredProps} />
      </DrawerContentScrollView>
    );
  }}>
  <Drawer.Screen
    name="FirstPage"
    options={{drawerLabel: 'First Page Option'}}
    component={firstScreenStack}
  />
  <Drawer.Screen
    name="SecondPage"
    options={{drawerLabel: 'Second Page Option'}}
    component={secondScreenStack}
  />
  <Drawer.Screen
    name="HiddenPage1"
    options={{drawerLabel: 'Hidden Page One option'}}
    component={thirdScreenStack}
  />
  <Drawer.Screen
    name="HiddenPage2"
    options={{drawerLabel: 'Hidden Page Two option'}}
    component={fourthScreenStack}
  />
</Drawer.Navigator>

Let’s get started 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 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 four files FirstPage.js, SecondPage.jsHiddenPage1.js, HiddenPage2.js in it.

hide_screen_from_drawer_menu_structure

Code

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

App.js

// How to Hide Navigation Option from Navigation Drawer / Sidebar
// https://aboutreact.com/how-to-hide-navigation-drawer-sidebar-option/

import 'react-native-gesture-handler';

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

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

import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
import HiddenPage1 from './pages/HiddenPage1';
import HiddenPage2 from './pages/HiddenPage2';

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}) => {
  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="FirstPage"
        component={FirstPage}
        options={{
          title: 'First Page', //Set Header Title
        }}
      />
    </Stack.Navigator>
  );
};

const secondScreenStack = ({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="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="HiddenPage1"
        component={HiddenPage1}
        options={{
          title: 'Hidder Page One', //Set Header Title
        }}
      />
    </Stack.Navigator>
  );
};

const fourthScreenStack = ({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="HiddenPage2"
        component={HiddenPage2}
        options={{
          title: 'Hidden Page Two', //Set Header Title
        }}
      />
    </Stack.Navigator>
  );
};

const App = () => {
  return (
    <NavigationContainer>
      <Drawer.Navigator
        drawerContentOptions={{
          activeTintColor: '#e91e63',
          itemStyle: {padding: 0},
        }}
        drawerContent={(props) => {
          const filteredProps = {
            ...props,
            state: {
              ...props.state,
              routeNames: props.state.routeNames.filter(
                // To hide single option
                // (routeName) => routeName !== 'HiddenPage1',
                // To hide multiple options you can add & condition
                (routeName) => {
                  routeName !== 'HiddenPage1'
                  && routeName !== 'HiddenPage2';
                },
              ),
              routes: props.state.routes.filter(
                (route) =>
                  route.name !== 'HiddenPage1'
                  && route.name !== 'HiddenPage2',
              ),
            },
          };
          return (
            <DrawerContentScrollView {...filteredProps}>
              <DrawerItemList {...filteredProps} />
            </DrawerContentScrollView>
          );
        }}>
        <Drawer.Screen
          name="FirstPage"
          options={{drawerLabel: 'First Page Option'}}
          component={firstScreenStack}
        />
        <Drawer.Screen
          name="SecondPage"
          options={{drawerLabel: 'Second Page Option'}}
          component={secondScreenStack}
        />
        <Drawer.Screen
          name="HiddenPage1"
          options={{drawerLabel: 'Hidden Page One option'}}
          component={thirdScreenStack}
        />
        <Drawer.Screen
          name="HiddenPage2"
          options={{drawerLabel: 'Hidden Page Two option'}}
          component={fourthScreenStack}
        />
      </Drawer.Navigator>
    </NavigationContainer>
  );
};

export default App;

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

FirstPage.js

// How to Hide Navigation Option from Navigation Drawer / Sidebar
// https://aboutreact.com/how-to-hide-navigation-drawer-sidebar-option/

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

const FirstPage = ({navigation}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View style={styles.container}>
          <Text style={styles.textStyle}>
            How to Hide Navigation Option from Navigation Drawer
            {'\n'}
            This is the First Page
          </Text>
          <Text
            style={{
              marginTop: 30,
              fontSize: 16,
              textAlign: 'center'
            }}>
            To Open Hidden Screen One which is in navigation drawer
            but without navigation option
          </Text>
          <Button
            title="Open Hidden Screen One"
            onPress={() => navigation.navigate('HiddenPage1')}
          />
          <Text
            style={{
              marginTop: 30,
              fontSize: 16,
              textAlign: 'center'
            }}>
            To Open Hidden Screen Two which is in navigation drawer
            but without navigation option
          </Text>
          <Button
            title="Open Hidden Screen Two"
            onPress={() => navigation.navigate('HiddenPage2')}
          />
        </View>
        <Text style={styles.footerHeading}>
          Hide Navigation Option from Navigation Drawer
        </Text>
        <Text style={styles.footerText}>www.aboutreact.com</Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {
    fontSize: 18,
    textAlign: 'center',
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

export default FirstPage;

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

SecondPage.js

// How to Hide Navigation Option from Navigation Drawer / Sidebar
// https://aboutreact.com/how-to-hide-navigation-drawer-sidebar-option/

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

const SecondPage = () => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View style={styles.container}>
          <Text style={styles.textStyle}>
            How to Hide Navigation Option from Navigation Drawer
            {'\n\n'}
            This is Second Page
          </Text>
        </View>
        <Text style={styles.footerHeading}>
          Hide Navigation Option from Navigation Drawer
        </Text>
        <Text style={styles.footerText}>www.aboutreact.com</Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {
    fontSize: 18,
    textAlign: 'center',
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

export default SecondPage;

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

HiddenPage1.js

// How to Hide Navigation Option from Navigation Drawer / Sidebar
// https://aboutreact.com/how-to-hide-navigation-drawer-sidebar-option/

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

const HiddenPage1 = ({navigation}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View style={styles.container}>
          <Text style={styles.textStyle}>
            How to Hide Navigation Option from Navigation Drawer
            {'\n\n'}
            This is Hidden Page One
          </Text>
          <Button
            title="Go Back"
            onPress={() => navigation.navigate('FirstPage')}
          />
        </View>
        <Text style={styles.footerHeading}>
          Hide Navigation Option from Navigation Drawer
        </Text>
        <Text style={styles.footerText}>www.aboutreact.com</Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {
    fontSize: 18,
    textAlign: 'center',
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

export default HiddenPage1;

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

HiddenPage2.js

// How to Hide Navigation Option from Navigation Drawer / Sidebar
// https://aboutreact.com/how-to-hide-navigation-drawer-sidebar-option/

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

const HiddenPage2 = ({navigation}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View style={styles.container}>
          <Text style={styles.textStyle}>
            How to Hide Navigation Option from Navigation Drawer
            {'\n\n'}
            This is Hidden Page One
          </Text>
          <Button
            title="Go Back"
            onPress={() => navigation.navigate('FirstPage')}
          />
        </View>
        <Text style={styles.footerHeading}>
          Hide Navigation Option from Navigation Drawer
        </Text>
        <Text style={styles.footerText}>www.aboutreact.com</Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {
    fontSize: 18,
    textAlign: 'center',
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

export default HiddenPage2;

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

hide_screen_from_drawer_menu1   hide_screen_from_drawer_menu2   hide_screen_from_drawer_menu3   hide_screen_from_drawer_menu4   hide_screen_from_drawer_menu5   hide_screen_from_drawer_menu6

Output in Online Emulator

This is How to Hide Navigation Option from Navigation Drawer / Sidebar in React Native. If you have any doubt 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. 🙂

2 thoughts on “How to Hide Navigation Option from Navigation Drawer / Sidebar”

Leave a Comment

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