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:
- Suppose your application has a user login as well as guest login for which you want to set the drawer options dynamically
- You have a multi-language application and you need to change the option labels in runtime
- You want to show the drawer navigation options on the basis of user permission
- 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 command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
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-screens
and react-native-safe-area-context
npm install react-native-screens react-native-safe-area-context --save
react-native-screens
package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java
file which is located in android/app/src/main/java/<your package name>/MainActivity.java
.
Add the following code to the body of MainActivity
class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
}
and make sure to add the following import statement at the top of this file below your package statement:
import android.os.Bundle;
This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.
3. For the Drawer Navigator install
npm install @react-navigation/drawer --save
4. Now we need to install and configure install react-native-gesture-handler
and react-native-reanimated
libraries that is required by the drawer navigator:
npm install react-native-gesture-handler react-native-reanimated --save
To configure react-native-reanimated
add Reanimated’s Babel plugin to your babel.config.js
(Reanimated plugin has to be listed last.)
module.exports = {
presets: [
...
],
plugins: [
... ,
'react-native-reanimated/plugin'
],
};
To configure 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 file, such as index.js
or App.js
import 'react-native-gesture-handler';
Note: If you are building for Android or iOS, do not skip this step, or your app may crash in production even if it works fine in development. This is not applicable to other platforms.
5. These steps are enough for the drawer navigation but in this example, we are also moving between screens so we will also need Stack Navigator
npm install @react-navigation/native-stack --save
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
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.
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 {Text} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-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 = createNativeStackNavigator();
const Drawer = createDrawerNavigator();
const FirstScreenStack = ({route}) => {
return (
<Stack.Navigator
initialRouteName="FirstPage"
screenOptions={{headerShown: false}}>
<Stack.Screen
name="FirstPage"
component={FirstPage}
initialParams={route.params}
/>
</Stack.Navigator>
);
};
const SecondScreenStack = () => {
return (
<Stack.Navigator
initialRouteName="SecondPage"
screenOptions={{headerShown: false}}>
<Stack.Screen
name="SecondPage"
component={SecondPage}
options={{
title: 'Second Page', //Set Header Title
}}
/>
</Stack.Navigator>
);
};
const ThirdScreenStack = () => {
return (
<Stack.Navigator screenOptions={{headerShown: false}}>
<Stack.Screen
name="ThirdPage"
component={ThirdPage}
options={{
title: 'Third Page', //Set Header Title
}}
/>
</Stack.Navigator>
);
};
const DrawerStack = ({route}) => {
return (
<Drawer.Navigator
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="FirstScreenStack"
options={{drawerLabel: 'First page Option'}}
component={FirstScreenStack}
initialParams={{userType: route.params.userType}}
/>
{route.params.userType === 'user' ? (
<>
<Drawer.Screen
name="SecondScreenStack"
options={{drawerLabel: 'Second page Option'}}
component={SecondScreenStack}
/>
<Drawer.Screen
name="ThirdScreenStack"
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
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
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. 🙂