React Native Popup Menu – Over Flow Menu

Popup Menu

React Native Popup Menu – Over Flow Menu is the most common thing that we can see in the Android applications. In the initial stage, the popup menu can be seen in the header only, but after the introduction of the material design, the popup menu can be seen in many places.

You can use the popup menu if you want to provide the number of options to select but don’t want to highlight them. Most developers use them when they provide 2-3 options to select and they don’t want to use navigation drawer (Side Menu).

How to use Menu Component for Popup Menu

<Menu
  // Referece for the Menu
  ref={(ref) => (_menu = ref)}
  button={
    // Setting up anchor for the popup menu
    // On click of this anchor over flow menu will popup
  }>
  <MenuItem
    onPress={ //Action on click of menu option// }>
    Menu Option display name
  </MenuItem>
  .....
  // To add the divider in between of the menu options
  <MenuDivider />
  <MenuItem disabled>
    Menu Option display name (Will be visible only)
  </MenuItem>
  ....
</Menu>

In this example, You will see how to generate the popup menu from the header or from anywhere. 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

To install any dependency first open the terminal and jump into your project

cd ProjectName

For the popup menu you can use react-native-material-menu which provides Menu, MenuItem, MenuDivider components to create over flow menu

npm install react-native-material-menu --save

We need React Navigation for this example as we will use header bar to setup menu and also we will switch the screen.

To add react-navigation and other supporting dependencies,

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 Stack Navigator install

npm install @react-navigation/stack --save

Note: When you use a navigator (such as stack 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 pages directory in your project, under this pages directory create FirstPage.js, SecondPage.js and CustomMaterialMenu.js

popup_menu_structure

App.js will have our Stack Navigator which is like an index file of our application. FirstPage.js and SecondPage.js will be the first and second screens of the application. We will use CustomMaterialMenu.js as custom popup menu component.

Code for Popup Menu

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

App.js

// React Native Popup Menu – Over Flow Menu
// https://aboutreact.com/react-native-popup-menu/

import 'react-native-gesture-handler';

import * as React from 'react';

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

import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
//import our Custom Icon menu component
import CustomMaterialMenu from './pages/CustomMaterialMenu';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="FirstPage"
        screenOptions={({route, navigation}) => ({
          headerRight: () => (
            <CustomMaterialMenu
              //Menu Text
              menutext="Menu"
              //Menu View Style
              menustyle={{marginRight: 16}}
              //Menu Text Style
              textStyle={{color: 'white'}}
              navigation={navigation}
              route={route}
              isIcon={true}
            />
          ),
        })}>
        <Stack.Screen
          name="FirstPage"
          component={FirstPage}
          options={{
            title: 'First Page', //Set Header Title
            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
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

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

FirstPage.js

// React Native Popup Menu – Over Flow Menu
// https://aboutreact.com/react-native-popup-menu/

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

const FirstPage = ({navigation, route}) => {
  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 of the app
          </Text>
          <Button
            onPress={() => navigation.navigate('SecondPage')}
            title="Go to Second Page"
          />
          <CustomMaterialMenu
            //Menu Text
            menutext="Show Menu"
            //Menu View Style
            menustyle={{
              margin: 10,
              flexDirection: 'row',
              justifyContent: 'flex-end',
            }}
            //Menu Text Style
            textStyle={{
              fontSize: 25,
              marginTop: 16,
              color: 'red',
            }}
            navigation={navigation}
            route={route}
            isIcon={false}
          />
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey',
          }}>
          Popup Menu – Over Flow Menu
        </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

// React Native Popup Menu – Over Flow Menu
// https://aboutreact.com/react-native-popup-menu/

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 of the App
          </Text>
          <Button
            title="Go back"
            onPress={() => navigation.goBack()}
          />
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey',
          }}>
          Popup Menu – Over Flow Menu
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey',
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default SecondPage;

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

CustomMaterialMenu

// React Native Popup Menu – Over Flow Menu
// https://aboutreact.com/react-native-popup-menu/

import React from 'react';
//import react in our code.
import {View, Text, Image, TouchableOpacity} from 'react-native';
//import all the components we are going to use.
import Menu, {MenuItem, MenuDivider} from 'react-native-material-menu';
//import menu and menu item

const CustomMaterialMenu = (props) => {
  let _menu = null;

  return (
    <View style={props.menustyle}>
      <Menu
        ref={(ref) => (_menu = ref)}
        button={
          props.isIcon ? (
            <TouchableOpacity onPress={() => _menu.show()}>
              <Image
                source={{
                  uri:
                    'https://raw.githubusercontent.com/AboutReact/sampleresource/master/menu_icon.png',
                }}
                style={{width: 30, height: 30}}
              />
            </TouchableOpacity>
          ) : (
            <Text
              onPress={() => _menu.show()}
               style={props.textStyle}>
              {props.menutext}
            </Text>
          )
        }>
        {props.route.name === 'FirstPage' ? (
          <MenuItem
            onPress={() => {
              props.navigation.navigate('SecondPage');
              _menu.hide();
            }}>
            Go to second Page
          </MenuItem>
        ) : null}
        {props.route.name === 'SecondPage' ? (
          <MenuItem
            onPress={() => {
              props.navigation.navigate('FirstPage');
              _menu.hide();
            }}>
            Go to first Page
          </MenuItem>
        ) : null}
        <MenuItem
          onPress={() => {
            _menu.hide();
          }}>
          Demo Option
        </MenuItem>
        <MenuItem disabled>Disabled option</MenuItem>
        <MenuDivider />
        <MenuItem
          onPress={() => {
            _menu.hide();
          }}>
          Option After Divider
        </MenuItem>
      </Menu>
    </View>
  );
};

export default CustomMaterialMenu;

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

                
      

Output in Online Emulator

That was the React Native Popup Menu. 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. 🙂

8 thoughts on “React Native Popup Menu – Over Flow Menu”

    • You can use style for the menu item styling and textStyle for the menu item text styling
      Ex.

      <MenuItem
        // For the menu item style
        style={{ backgroundColor: 'blue' }}
        // For the menu item text style
        textStyle={{ color: 'green' , fontSize: 20}}
        onPress={() => {
          ......
        }}
      >
        Go to second Page
      </MenuItem>
      Reply

Leave a Comment

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